题
与我之前的问题,如何将字符串列表加入字符串,以便干净地引用值。类似的东西:
['a', 'one "two" three', 'foo, bar', """both"'"""]
成:
a, 'one "two" three', "foo, bar", "both\"'"
我怀疑csv模块会在这里发挥作用,但我不知道如何获得我想要的输出。
解决方案
使用 csv
模块,您可以这样做:
import csv
writer = csv.writer(open("some.csv", "wb"))
writer.writerow(the_list)
如果您需要字符串,只需使用 StringIO
实例作为文件:
f = StringIO.StringIO()
writer = csv.writer(f)
writer.writerow(the_list)
print f.getvalue()
输出: a,“one”"“two”"三个“,”foo,bar",“”和“"”"
csv
将以稍后可以回读的方式编写。
您可以通过定义 dialect
来微调其输出,只需根据需要设置 quotechar
, escapechar
等:
class SomeDialect(csv.excel):
delimiter = ','
quotechar = '"'
escapechar = "\\"
doublequote = False
lineterminator = '\n'
quoting = csv.QUOTE_MINIMAL
f = cStringIO.StringIO()
writer = csv.writer(f, dialect=SomeDialect)
writer.writerow(the_list)
print f.getvalue()
输出: a,one \“two \”三,“foo,bar”,两者都是''
相同的方言可以与csv模块一起使用,以便稍后将字符串读回列表。
其他提示
在相关的说明中,Python的内置编码器也可以进行字符串转义:
>>> print "that's interesting".encode('string_escape')
that\'s interesting
这是一个稍微简单的替代方案。
def quote(s):
if "'" in s or '"' in s or "," in str(s):
return repr(s)
return s
我们只需引用可能包含逗号或引号的值。
>>> x= ['a', 'one "two" three', 'foo, bar', 'both"\'']
>>> print ", ".join( map(quote,x) )
a, 'one "two" three', 'foo, bar', 'both"\''
不隶属于 StackOverflow