简体   繁体   English

如何在Python中将字符串连接成括号

[英]How to concatenate strings into parenthesis in Python

In Python I have this loop that eg prints some value: 在Python中,我有一个循环,例如打印一些值:

for row in rows:
    toWrite = row[0]+","
    toWrite += row[1]
    toWrite += "\n"

Now this works just fine, and if I print "toWrite" it would print this: 现在这可以正常工作,如果我打印“ toWrite”,它将打印以下内容:

print toWrite

#result:,
A,B
C,D
E,F
... etc

My question is, how would I concatenate these strings with parenthesis and separated with commas, so result of loop would be like this: 我的问题是,我该如何用括号将这些字符串连接起来并用逗号分隔,所以循环的结果将如下所示:

(A,B),(C,D),(E,F) <-- the last item in parenthesis, should not contain - end with comma

You'd group your items into pairs , then use string formatting and str.join() : 您可以将项目成对分组 ,然后使用字符串格式和str.join()

','.join(['({},{})'.format(*pair) for pair in zip(*[iter(rows)] * 2)])
  • The zip(*[iter(rows)] * 2) expression produces elements from rows in pairs. zip(*[iter(rows)] * 2)表达式从成对的rows中生成元素。
  • Each pair is formatted with '({},{})'.format(*pair) ; 每对均以'({},{})'.format(*pair) the two values in pair are slotted into each {} placeholder. pair的两个值插入到每个{}占位符中。
  • The (A,B) strings are joined together into one long string using ','.join() . 使用','.join()(A,B)字符串连接在一起成为一个长字符串。 Passing in a list comprehension is marginally faster than using a generator expression here as str.join() would otherwise convert it to a list anyway to be able to scan it twice (once for the output size calculation, once for building the output). 传递列表str.join()比在这里使用生成器表达式要快一些,因为str.join()否则无论如何都会将其转换为列表以便能够对其进行两次扫描(一次用于输出大小计算,一次用于构建输出)。

Demo: 演示:

>>> rows = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
>>> ','.join(['({},{})'.format(*pair) for pair in zip(*[iter(rows)] * 2)])
'(A,B),(C,D),(E,F),(G,H)'

Try this: 尝试这个:

from itertools import islice, izip
','.join(('(%s, %s)' % (x, y) for x, y in izip(islice(rows, 0, None, 2), islice(rows, 1, None, 2))))

Generator and iterators are adopted here. 这里采用生成器和迭代器。 See itertools for a reference. 请参阅itertools以获取参考。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM