|
| 1 | +🔓**Python `.join()` Power and Secret Tips/Tricks**: |
| 2 | + |
| 3 | +1. **String Concatenation with `.join()`**: Instead of using `+` for string concatenation, use `.join()` for better performance, especially with large strings. |
| 4 | + ```python |
| 5 | + words = ['Hello', 'world', '!'] |
| 6 | + sentence = ' '.join(words) |
| 7 | + ``` |
| 8 | + |
| 9 | +2. **List to String Conversion**: Use `.join()` to convert a list of strings into a single string efficiently. |
| 10 | + ```python |
| 11 | + words = ['Python', 'is', 'awesome'] |
| 12 | + sentence = ' '.join(words) |
| 13 | + ``` |
| 14 | + |
| 15 | +3. **Joining Iterable of Integers**: Convert a list of integers to a single string efficiently. |
| 16 | + ```python |
| 17 | + numbers = [1, 2, 3, 4, 5] |
| 18 | + num_string = ''.join(map(str, numbers)) |
| 19 | + ``` |
| 20 | + |
| 21 | +4. **Joining Generator Expression**: Utilize a generator expression within `.join()` for memory efficiency. |
| 22 | + ```python |
| 23 | + data = ['a' * i for i in range(100000)] |
| 24 | + result = ''.join(item for item in data) |
| 25 | + ``` |
| 26 | + |
| 27 | +5. **Custom Delimiter**: Specify a custom delimiter other than space for joining elements. |
| 28 | + ```python |
| 29 | + words = ['apple', 'banana', 'orange'] |
| 30 | + csv_string = ','.join(words) |
| 31 | + ``` |
| 32 | + |
| 33 | +6. **Joining Nested Lists**: Flatten a nested list efficiently using `.join()` with list comprehension. |
| 34 | + ```python |
| 35 | + nested_list = [['a', 'b', 'c'], ['1', '2', '3'], ['x', 'y', 'z']] |
| 36 | + flat_list = ''.join(item for sublist in nested_list for item in sublist) |
| 37 | + ``` |
| 38 | + |
| 39 | +7. **Joining Lines from File**: Concatenate lines from a file efficiently using `.join()` and file reading. |
| 40 | + ```python |
| 41 | + with open('file.txt', 'r') as file: |
| 42 | + file_content = ''.join(file.readlines()) |
| 43 | + ``` |
| 44 | + |
| 45 | +8. **Joining Elements with Formatting**: Apply formatting while joining elements for custom output. |
| 46 | + ```python |
| 47 | + data = [('apple', 3), ('banana', 5), ('orange', 2)] |
| 48 | + output = '\n'.join(f'{item[0]}: {item[1]}' for item in data) |
| 49 | + ``` |
| 50 | + |
| 51 | +9. **Joining Set of Strings**: Join a set of strings while preserving uniqueness and order. |
| 52 | + ```python |
| 53 | + unique_words = {'apple', 'banana', 'orange'} |
| 54 | + sentence = ' '.join(unique_words) |
| 55 | + ``` |
| 56 | + |
| 57 | +10. **Joining with Newline Character**: Concatenate elements with newline character for multiline output. |
| 58 | + ```python |
| 59 | + lines = ['First line', 'Second line', 'Third line'] |
| 60 | + multiline_string = '\n'.join(lines) |
| 61 | + ``` |
0 commit comments