python how to print list of strings with double quotes

非 Y 不嫁゛ 提交于 2019-12-12 01:37:43

问题


I have a list i.e.

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

i.e. 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


回答1:


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):

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



回答2:


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:

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"



回答3:


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



回答4:


>>> print '"' + '"|"'.join(my_list) + '"'
"a"|"b"|"c"|"d"|"e"|"f"


来源:https://stackoverflow.com/questions/36297819/python-how-to-print-list-of-strings-with-double-quotes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!