Convert a list of integers to string

Question:

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'
Asked By: Mira Mira

||

Answers:

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)
Answered By: jgritty

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

''.join(map(str,new))
Answered By: tynn

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'ntx05x00x06x05'

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?

Answered By: jloup

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)
Answered By: Cherry

Two simple ways of doing this:

"".join(map(str, A))
"".join(str(a) for a in A)
Answered By: Satyam Singh

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.

Answered By: Paul P
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.