Skip to content Skip to sidebar Skip to footer

Python How To Print List Of Strings With Double Quotes

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 pipe

Solution 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"

Solution 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"

Solution 3:

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

Solution 4:

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

Post a Comment for "Python How To Print List Of Strings With Double Quotes"