How can I join a list into a string (caveat)?

Along the lines of my previous question, how can i join a list of strings into a string such that values get quoted cleanly. Something like:

['a', 'one "two" three', 'foo, bar', """both"'"""]


a, 'one "two" three', "foo, bar", "both\"'"

I suspect that the csv module will come into play here, but i'm not sure how to get the output I want.

Asked by: Sophia801 | Posted: 28-01-2022

Answer 1

Using the csv module you can do that way:

import csv
writer = csv.writer(open("some.csv", "wb"))

If you need a string just use StringIO instance as a file:

f = StringIO.StringIO()
writer = csv.writer(f)
print f.getvalue()

The output: a,"one ""two"" three","foo, bar","both""'"

csv will write in a way it can read back later. You can fine-tune its output by defining a dialect, just set quotechar, escapechar, etc, as needed:

class SomeDialect(csv.excel):
    delimiter = ','
    quotechar = '"'
    escapechar = "\\"
    doublequote = False
    lineterminator = '\n'
    quoting = csv.QUOTE_MINIMAL

f = cStringIO.StringIO()
writer = csv.writer(f, dialect=SomeDialect)
print f.getvalue()

The output: a,one \"two\" three,"foo, bar",both\"'

The same dialect can be used with csv module to read the string back later to a list.

Answered by: Aida275 | Posted: 01-03-2022

Answer 2

On a related note, Python's builtin encoders can also do string escaping:

>>> print "that's interesting".encode('string_escape')
that\'s interesting

Answered by: Carlos938 | Posted: 01-03-2022

Answer 3

Here's a slightly simpler alternative.

def quote(s):
    if "'" in s or '"' in s or "," in str(s):
        return repr(s)
    return s

We only need to quote a value that might have commas or quotes.

>>> x= ['a', 'one "two" three', 'foo, bar', 'both"\'']
>>> print ", ".join( map(quote,x) )
a, 'one "two" three', 'foo, bar', 'both"\''

Answered by: Miranda308 | Posted: 01-03-2022

Similar questions

Still can't find your answer? Check out these communities...

PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python