开发者

python string formatting: way to not use two lists?

开发者 https://www.devze.com 2023-03-01 23:24 出处:网络
With the following code: a = [\'foo\', \'bar\', \'doh\', \'rae\'] I\'d like the string SUM(foo) AS foo, SUM(bar) AS bar, SUM(doh) AS doh, SUM(rae) AS rae. This works:

With the following code:

a = ['foo', 'bar', 'doh', 'rae']

I'd like the string SUM(foo) AS foo, SUM(bar) AS bar, SUM(doh) AS doh, SUM(rae) AS rae. This works:

Tried something clever like 'SUM(%s) AS %s' % ([x for x in a], [x for x in a]) but obviously it didn't work, and using two li开发者_StackOverflowst comprehensions felt woefully inefficient.

Any tips?


Why not use the str.format method?

", ".join(['SUM({n}) AS {n}'.format(n=x) for x in a])
# Returns SUM(foo) AS foo, SUM(bar) AS bar, SUM(doh) AS doh, SUM(rae) AS rae

If a is a large list, you may want to use a generator instead, in order to avoid creating the whole list in memory first, as GWW points out.

", ".join('SUM({n}) AS {n}'.format(n=x) for x in a)


you can use a str.format function to deliver one argumet twice in a string, something like that:

s = ', '.join(['SUM({0}) AS {0}'.format(x) for x in a])

and with one list comprehension and a join operation it produces desired output

'SUM(foo) AS foo, SUM(bar) AS bar, SUM(doh) AS doh, SUM(rae) AS rae'

Greetings!

0

精彩评论

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

关注公众号