如何将列表加入字符串(caveat)?

时间:2020-03-06 14:34:25  来源:igfitidea点击:

沿着我之前的问题,我如何将字符串列表连接到字符串中,使值被清晰地引用。就像是:

['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,"一个"""两个""三个"," foo,bar","两个""'"

csv将会以一种可以稍后读取的方式编写。
我们可以通过定义"方言"来微调其输出,只需根据需要设置" 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 \" Three," foo,bar",both \"'

相同的方言可与csv模块一起使用,以稍后将字符串读回到列表中。

这是一个稍微简单的选择。

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"\''

值得一提的是,Python的内置编码器还可以进行字符串转义:

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