Python Forum
Convert list of numbers to string of numbers - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Convert list of numbers to string of numbers (/thread-31074.html)



Convert list of numbers to string of numbers - kam_uk - Nov-21-2020

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?


RE: Convert list of numbers to string of numbers - Larz60+ - Nov-21-2020

Use: My_String = ' '.join([str(x) for x in My_list])
you need to convert the individual integers to strings before join.


RE: Convert list of numbers to string of numbers - kam_uk - Nov-21-2020

Thanks, can you explain the code to me and why we are doing this? What is wrong with my first line?


RE: Convert list of numbers to string of numbers - Larz60+ - Nov-21-2020

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.


RE: Convert list of numbers to string of numbers - ndc85430 - Nov-21-2020

As for why, because join takes an iterable of strings, not an iterable of anything else, per the documentation.


RE: Convert list of numbers to string of numbers - deanhystad - Nov-21-2020

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 [].