如何“正确"打印列表? [英] How to "properly" print a list?
本文介绍了如何“正确"打印列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我有一个清单:
['x', 3, 'b']
我希望输出是:
[x, 3, b]
我如何在 python 中做到这一点?
How can I do this in python?
如果我执行 str(['x', 3, 'b'])
,我会得到一个带引号的,但我不需要引号.
If I do str(['x', 3, 'b'])
, I get one with quotes, but I don't want quotes.
推荐答案
在 Python 2 中:
In Python 2:
mylist = ['x', 3, 'b']
print '[%s]' % ', '.join(map(str, mylist))
在 Python 3 中(其中 print
是一个内置函数,不再是语法特性):
In Python 3 (where print
is a builtin function and not a syntax feature anymore):
mylist = ['x', 3, 'b']
print('[%s]' % ', '.join(map(str, mylist)))
两者都返回:
[x, 3, b]
这是使用 map()
函数为 mylist 的每个元素调用 str,创建一个新的字符串列表,然后使用 str.join()
.然后,%
字符串格式化操作符将替换 "[%s]"
中的 %s
中的字符串.
This is using the map()
function to call str for each element of mylist, creating a new list of strings that is then joined into one string with str.join()
. Then, the %
string formatting operator substitutes the string in instead of %s
in "[%s]"
.
这篇关于如何“正确"打印列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文