Python Forum
Convert list of numbers to string of numbers
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Convert list of numbers to string of numbers
#1
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?
Reply
#2
Use: My_String = ' '.join([str(x) for x in My_list])
you need to convert the individual integers to strings before join.
ndc85430 likes this post
Reply
#3
Thanks, can you explain the code to me and why we are doing this? What is wrong with my first line?
Reply
#4
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.
Reply
#5
As for why, because join takes an iterable of strings, not an iterable of anything else, per the documentation.
Reply
#6
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 [].
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Random Generator: From Word to Numbers, from Numbers to n possibles Words Yamiyozx 2 1,369 Jan-02-2023, 05:08 PM
Last Post: deanhystad
  Python OOP - two numbers ben1122 31 7,844 Oct-02-2021, 01:03 PM
Last Post: ben1122
  How to convert every even number in a list to odd? Bruizeh 4 3,666 Aug-27-2021, 03:04 AM
Last Post: naughtyCat
  Check if all the numbers are higher than five and if not... banidjamali 3 2,059 Jan-11-2021, 11:25 AM
Last Post: banidjamali
  Counting numbers in other lines LewAlbert 6 99,271 Dec-12-2020, 07:38 PM
Last Post: deanhystad
  How can I found how many numbers are there in a Collatz Sequence that I found? cananb 5 3,693 Nov-23-2020, 05:15 PM
Last Post: cananb
  Getting largest indices of array less than or equal to an array of numbers schniefen 5 2,582 Nov-02-2020, 08:14 PM
Last Post: schniefen
  Positive and negative numbers in a row peterp 1 1,721 Oct-29-2020, 02:42 AM
Last Post: deanhystad
  Printing sequence of numbers kam_uk 1 2,797 Sep-27-2020, 01:50 PM
Last Post: perfringo
  Convert multiple decimal numbers in string to floats Katy8 6 3,462 Aug-16-2020, 06:06 PM
Last Post: Katy8

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020