Borislav Hadzhiev
Last updated: Jun 18, 2022
Check out my new book
To join a list of integers into a string:
map()
function to convert the integers in the list to stings.str.join()
method on a string separator.map
object to the join()
method.my_list = [1, 2, 3, 4, 5] my_str = ', '.join(map(str, my_list)) print(my_str) # 👉️ "1, 2, 3, 4, 5"
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.The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.
my_list = [1, 2, 3, 4, 5] # 👇️ ['1', '2', '3', '4', '5'] print(list(map(str, my_list)))
We simply passed each integer to the str()
class to get a map
object that
only contains strings.
The string the join()
method is called on is used as the separator between
elements.
my_list = [1, 2, 3, 4, 5] my_str = '-'.join(map(str, my_list)) print(my_str) # 👉️ "1-2-3-4-5"
If you don't need a separator and just want to join the iterable's elements into
a string, call the join()
method on an empty string.
my_list = [1, 2, 3, 4, 5] my_str = ''.join(map(str, my_list)) print(my_str) # 👉️ "12345"
This approach also works if your list contains both strings and integers.
my_list = [1, 'a', 2, 'b', 3, 'c', 4, 'd', 5] my_str = ', '.join(map(str, my_list)) print(my_str) # 👉️ "1, a, 2, b, 3, c, 4, d, 5"
Alternatively, you can pass a generator expression to the join()
method.
To join a list of integers into a string:
join()
method on a string separator.join()
method.str()
class to convert it to a
string.my_list = [1, 2, 3, 4, 5] result = ', '.join(str(item) for item in my_list) print(result) # 👉️ "1, 2, 3, 4, 5"
We used a generator expression to convert each item to a string by passing it to
the str()
class.