Borislav Hadzhiev
Sat Jun 18 2022·2 min read
Photo by Hunter Reilly
To convert a list of characters into a string:
str.join()
method on a string separator.join()
method.my_list = ['a', 'b', 'c'] # 👇️ without a separator my_str = ''.join(my_list) print(my_str) # 👉️ 'abc' # 👇️ with a space separator print(' '.join(my_list)) # 👉️ 'a b c' # 👇️ with a hyphen separator print('-'.join(my_list)) # 👉️ 'a-b-c'
The str.join method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.
TypeError
if there are any non-string values in the iterable.If your list contains numbers, or other types, convert all of the values to
string before calling join()
.
my_list = ['a', 'b', 'c', 1, 2, 3] my_str = ', '.join(map(str, my_list)) print(my_str) # 👉️ 'a, b, c, 1, 2, 3'
The map() function takes a function and an iterable as arguments and calls the function on each item of the iterable.
str.join()
method.The string the join()
method is called on is used as the separator between
elements.
my_list = ['a', 'b', 'c'] my_str = '-'.join(my_list) print(my_str) # 👉️ 'a-b-c'
If you need to join the list of characters with spaces, call the method on a string that contains a space.
my_list = ['a', 'b', 'c'] my_str = ' '.join(my_list) print(my_str) # 👉️ 'a b c'
Similarly, you can use a newline (\n
) to join the characters in the list with
a newline character.
my_list = ['a', 'b', 'c'] my_str = '\n'.join(my_list) # a # b # c print(my_str)
If you don't need a separator and just want to join the list's elements into a
string, call the join()
method on an empty string.
my_list = ['a', 'b', 'c'] my_str = ''.join(my_list) print(my_str) # 👉️ abc