简体   繁体   English

python如何打印带有双引号的字符串列表

[英]python how to print list of strings with double quotes

I have a list ie 我有一个清单,即

my_list = ['a', 'b', 'c', 'd','e','f']

I want to print this out in a pipe or comma delimited format, but because some of my list objects can have commas or pipes, I would like to wrap double quotes around each object when I print 我想以竖线或逗号分隔格式将其打印出来,但是由于我的某些列表对象可以带有逗号或竖线,因此我想在打印时在每个对象周围用双引号引起来

ie the output should be 即输出应为

"a"|"b"|"c"|"d"|"e"|"f" rather than a|b|c|d|e|f

i can't use format on my version of python 我无法在我的python版本上使用格式

Create a generator that formats each element, then unpack it and use a custom separator. 创建一个格式化每个元素的生成器,然后解压缩它并使用自定义分隔符。 If you are using Python 2, import the print() function first (this can be safely done in Python 3 as well): 如果您使用的是Python 2,请先import print()函数(这也可以在Python 3中安全地完成):

>>> from __future__ import print_function
>>> print(*('"{}"'.format(item) for item in my_list), sep='|')
"a"|"b"|"c"|"d"|"e"|"f"

Don't do this yourself. 不要自己做。 You'll trip yourself trying to handle all the corner cases. 您会绊倒自己,尝试处理所有极端情况。 (What if your fields can have double quotes in them?) Use the csv module instead: (如果您的字段中可以包含双引号怎么办?)请改用csv模块:

s = StringIO()
writer = csv.writer(s, delimiter="|")
writer.writerow(["a", "b", "c", "d,", "e|", "foo\"bar"])
print i.getvalue()

You get: 你得到:

a|b|c|d,|"e|"|"foo""bar"
>>> "|".join(['"{0}"'.format(x) for x in my_list])
"a"|"b"|"c"|"d"|"e"|"f"
>>> print '"' + '"|"'.join(my_list) + '"'
"a"|"b"|"c"|"d"|"e"|"f"

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

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