Use join() Function in Python with Example

The `join()` function in Python is used to concatenate the elements of an iterable (like a list or tuple) into a single string. The elements are joined together using a specified separator.

Syntax

separator_string.join(iterable)

– separator_string: The string that will be placed between each element of the iterable.
– iterable: The iterable containing strings to be joined. The elements must all be strings.

Example 1: Joining a List of Strings

```python
words = ["Hello", "world", "this", "is", "Python"]
separator = " "
sentence = separator.join(words)
print(sentence)
```

Output

```
Hello world this is Python
```

Explanation

– The list `words` contains several strings.
– The `join()` function is used with a space `” “` as the separator to combine the elements into a single string, resulting in a sentence.

Example 2: Joining a List of Strings with a Comma

```python
fruits = ["apple", "banana", "cherry"]
separator = ", "
result = separator.join(fruits)
print(result)
```

Output

```
apple, banana, cherry
```

Explanation

– The list `fruits` contains the names of different fruits.
– The `join()` function uses a comma followed by a space `”, “` as the separator to join the elements into a single string.

Example 3: Joining with an Empty String (No Separator)

```python
letters = ["P", "y", "t", "h", "o", "n"]
result = "".join(letters)
print(result)
```

Output

```
Python
```

Explanation

– The list `letters` contains individual characters of the word “Python”.
– The `join()` function is used with an empty string `””` as the separator, resulting in the characters being joined together without any space between them.

Example 4: Joining a Tuple of Strings

```python
names = ("Alice", "Bob", "Charlie")
separator = " & "
result = separator.join(names)
print(result)
```

Output

```
Alice & Bob & Charlie
```

Explanation

– The tuple `names` contains different names.
– The `join()` function uses the separator `” & “` to join the names together in a single string.

Important Notes

– All elements in the iterable must be strings. If they are not, you’ll need to convert them to strings using `str()` before using `join()`.
– The `join()` function does not modify the original iterable but returns a new string.