显示列表元素,就好像它们是输入的一样

Display list elements as if they were typed in

代码如下:

test = ['26', 1, '050120', '084922', u'43034775', u'RRR', '', None]
print(', '.join(test))

它说:

TypeError: sequence item 1: expected str instance, int found

有没有不看元素类型就加入的方法?

', '.join(str(v) for v in test)

不是一个好的解决方案。它打印:

26, 1, 050120, 084900, 21747, 1200.0, X, X, 18034775, 5TDDK3DC4BS029227, , None

我想保留元素类型并按原样打印:

'26', 1, '050120', '084922', u'43034775', u'RRR', '', None

您可以使用 repr 内置函数。

print(', '.join(map(repr, test)))

这会产生所需的输出,因为

For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval()

示例:

>>> str(1)
'1'
>>> str('1')
'1'
>>> repr(1)
'1'
>>> repr('1')
"'1'"

如果只是为了打印目的:

test = ['26', 1, '050120', '084922', u'43034775', u'RRR', '', None]

print(str(test)[1:-1])

到您预期的输出'26', 1, '050120', '084922', u'43034775', u'RRR', '', None。使用列表的格式并删除括号

test = ['26', 1, '050120', '084922', u'43034775', u'RRR', '', None]
print(str(test).strip("[]")) # '26', 1, '050120', '084922', '43034775', 'RRR', '', None