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'
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'
With Convert a list of characters into a string you can just do
''.join(map(str,new))
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)
Two simple ways of doing this:
"".join(map(str, A))
"".join(str(a) for a in A)
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/
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
.
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)