25

I want to convert my list of integers into a string. Here is how I create the list of integers:

new = [0] * 6
for i in range(6):
    new[i] = random.randint(0,10)

Like this:

new == [1,2,3,4,5,6]
output == '123456'
Georgy
  • 9,972
  • 7
  • 57
  • 66
Mira Mira
  • 1,305
  • 3
  • 11
  • 18

6 Answers6

57

With Convert a list of characters into a string you can just do

''.join(map(str,new))
Community
  • 1
  • 1
tynn
  • 36,131
  • 8
  • 97
  • 135
14

There's definitely a slicker way to do this, but here's a very straight forward way:

mystring = ""

for digit in new:
    mystring += str(digit)
jgritty
  • 11,242
  • 3
  • 35
  • 58
8

two simple ways of doing this

"".join(map(str, A))
"".join([str(a) for a in A])
Satyam Singh
  • 249
  • 3
  • 3
1

Coming a bit late and somehow extending the question, but you could leverage the array module and use:

from array import array

array('B', new).tobytes()

b'\n\t\x05\x00\x06\x05'

In practice, it creates an array of 1-byte wide integers (argument 'B') from your list of integers. The array is then converted to a string as a binary data structure, so the output won't look as you expect (you can fix this point with decode()). Yet, it should be one of the fastest integer-to-string conversion methods and it should save some memory. See also documentation and related questions:

https://www.python.org/doc/essays/list2str/

https://docs.python.org/3/library/array.html#module-array

Converting integer to string in Python?

Community
  • 1
  • 1
jloup
  • 21
  • 2
1

If you don't like map():

new = [1, 2, 3, 4, 5, 6]

output = "".join(str(i) for i in new)
# '123456'

Keep in mind, str.join() accepts an iterable so there's no need to convert the argument to a list.

Paul P
  • 2,239
  • 2
  • 6
  • 20
-3

You can loop through the integers in the list while converting to string type and appending to "string" variable.

for int in list:
    string += str(int)
Cherry
  • 63
  • 1
  • 9