开发者

Python join - quoting values

I am using the Python join function to create a string e.g.

a = [a, b, c, d]
b = ",".join(a)
print b

b = a,b,c,d

but I want

b = 'a','b','c','d'

is there a way to do this just using the join function (or a shorter way) rather than doing

b = ""
for x in a:
  b += "'%s'," % x
b =开发者_JS百科 b[:-1]


b = ",".join(map(repr, a))

Will also correctly escape characters inside the string which may be useful.


In [1]: a = ['a', 'b', 'c', 'd']

In [2]: print ','.join("'%s'" % x for x in a)
'a','b','c','d'


>>> b = ['a', 'b', 'c', 'd']
>>> print ','.join("'{0}'".format(s) for s in b)
'a','b','c','d'

The expression inside the join() is a generator expression.


b = "'" + "','".join(a) + "'"

:)


a = ['a', 'b', 'c', 'd']

b = "','".join(a).join("''")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜