Python Forum

Full Version: Convert list of numbers to string of numbers
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi

I have a list

My_list = [1, 2, 3, 4, 5]
I want to convert each number from an integer to a string.

I would normally use

My_string = ''.join(My_list)
but that doesn't appear to work.... what am I doing wrong?
Use: My_String = ' '.join([str(x) for x in My_list])
you need to convert the individual integers to strings before join.
Thanks, can you explain the code to me and why we are doing this? What is wrong with my first line?
each item in the original list is an integer.
the list comprehension ( [str(x) for x in My_list] )converts each to a string prior to the join.
As for why, because join takes an iterable of strings, not an iterable of anything else, per the documentation.
The list comprehension is a compact way to create a list. This
My_string = ''.join([str(num) for num in My_list])
is the same as
temp = []
for num in My_list:
    temp.append(str(num))
My_string = ''.join(temp)
With the construction of the temp list being done by the code between the [].