用 ' 或 " 打印列表
我在想,当我打印一个单词列表时,如果其中一个单词是“it's”,那么列表在屏幕上显示为 ['joe', 'bob', "it's"]
。你会注意到,joe 和 bob 是用 '
括起来的,而 it's 是用 "
括起来的。
问题是:有没有办法让所有列表项都用 "
来打印,而不是 '
,这样 print(mylist)
的输出就会变成 ["joe", "bob", "it's"]
呢?
我查了一下关于打印列表和打印函数的资料,但似乎没有相关的文档说明这个可以调整。看起来在使用打印语句时,列表的格式是预设的。我只是好奇。
这段内容是关于 Python 的。
1 个回答
0
一个很不错的技巧是使用 json.dumps
import json
words = ["joe", "it's","bob", 'te"st']
print(json.dumps(l))
# outputs ["joe", "it's", "bob", "te\"st"]
或者可以用一种比较“hacky”的方法:
words = ["joe", "it's","bob", 'te"st']
format = '["' + '", "'.join(words) + '"]'
print(format)
# outputs ["joe", "it's", "bob", "te"st"]
# note the unescaped double quote
你也可以看看 这个回答,它使用了 black
模块。
无论如何,这完全是一个“打印”的问题,对列表中项目的“值”没有任何影响。