31

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
  • 12,464
  • 7
  • 65
  • 73
Mira Mira
  • 1,385
  • 3
  • 11
  • 18

6 Answers6

66

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

''.join(map(str,new))
Community
  • 1
  • 1
tynn
  • 38,113
  • 8
  • 108
  • 143
13

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,660
  • 3
  • 38
  • 60
12

Two simple ways of doing this:

"".join(map(str, A))
"".join(str(a) for a in A)
Community
  • 1
  • 1
Satyam Singh
  • 349
  • 3
  • 4
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
  • 3,346
  • 2
  • 12
  • 26
-4

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
  • 61
  • 1
  • 1
  • 9