How to use join() in Python

The ‘join()‘ method in Python can be used to concatenate items of an iterable (such as a list, tuple or string) into a single string:

1. To join the items of a list of strings into a single string:

my_list = ["apple", "grape", "mango", "peach", "lemon"]

my_string = ", ".join(my_list)

print(my_string)
print(type(my_string))

The result:

apple, grape, mango, peach, lemon
<class 'str'>

2. To join the items of a list of numbers into a single string:

my_list = [1, 2, 3, 4, 5]

my_string = "".join([str(i) for i in my_list])

print(my_string)
print(type(my_string))

The result:

12345
<class 'str'>

3. To join the items of a tuple into a single string:

my_tuple = ("apple", "grape", "mango", "peach", "lemon")

my_string = " | ".join(my_tuple)

print(my_string)
print(type(my_string))

The result

apple | grape | mango | peach | lemon
<class 'str'>

4. To join the characters of a string into a single string:

string_example = "Hello"

my_string = "-".join(string_example)

print(my_string)
print(type(my_string))

The result:

H-e-l-l-o
<class 'str'>

Additional Topics

Leave a Comment