将列表项转换为字符串

时间:2014-04-26 06:56:50

标签: python arrays string itertools

我是Python的新手,多年来依靠PHP作为我选择的服务器端脚本语言。我使用Python Itertools生成了一个可以排列6位数字的组合列表。

import itertools
import threading

def test(full) :
   #print full
   codes = list(itertools.product([1,2,3,4,5,6,7,8,9,0], repeat=6))
   count = len(codes)

   for num in range(0, count):
       item = codes[num]
       print item

item将返回为看起来像数组的内容。它总是由逗号和括号内部分隔的一系列6个数字。

(0, 1, 2, 3, 4, 5)

如何将上述值格式化为如下所示?

012345

由于

3 个答案:

答案 0 :(得分:3)

这是一个很好的方法

>>> from itertools import imap
>>> ''.join(imap(str, item))
012345

答案 1 :(得分:2)

>>> series = (0, 1, 2, 3, 4, 5)
>>> ''.join(str(x) for x in series)
012345

上面的代码将为您提供一个包含(0, 1, 2, 3, 4, 5)元组中所有元素的字符串。您也可以将其转换为int类型(前导零赢得保留):

>>> int(''.join(str(x) for x in series))
12345

答案 2 :(得分:2)

看似数组的内容实际上是tuple。但这并不重要,因为您可以使用str.join方法从任何可迭代的元素中创建一个字符串(假设这些元素可以转换为str):

>>> tpl = (0, 1, 2, 3, 4, 5)
>>> s = ''.join(str(i) for i in tpl)
>>> print s
012345

您可以通过在交互式口译员中输入str.join来获取有关help(str.join)的更多信息。