简体   繁体   English

将整数列表转换为字符串

[英]Convert a list of integers to string

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'

使用Convert a list of characters into a string你可以做

''.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:来得有点晚,并以某种方式扩展了问题,但您可以利用array模块并使用:

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.实际上,它会从您的整数列表中创建一个 1 字节宽的整数数组(参数'B' )。 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() ).然后将数组转换为字符串作为二进制数据结构,因此输出看起来不会像您预期的那样(您可以使用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://www.python.org/doc/essays/list2str/

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

Converting integer to string in Python? 在 Python 中将整数转换为字符串?

If you don't like map() :如果你不喜欢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 .请记住, str.join()接受可迭代对象,因此无需将参数转换为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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM