Python 如何将列表加入字符串(警告)?
按照我上一篇文章的思路,我如何将字符串列表连接到一个字符串中,从而使值被清晰地引用。比如:Python 如何将列表加入字符串(警告)?,python,string,list,csv,Python,String,List,Csv,按照我上一篇文章的思路,我如何将字符串列表连接到一个字符串中,从而使值被清晰地引用。比如: ['a', 'one "two" three', 'foo, bar', """both"'"""] 进入: 我怀疑csv模块将在这里发挥作用,但我不确定如何获得我想要的输出。使用csv模块,您可以这样做: import csv writer = csv.writer(open("some.csv", "wb")) writer.writerow(the_list) 如果需要字符串,只需使用Strin
['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,一个“两个”三个,“foo,bar”,两个“
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
+1虽然这本身不是我想要的,但我可以看到这在某种程度上对我很有帮助。
>>> print "that's interesting".encode('string_escape')
that\'s interesting