如何将字符串连接到 Python 中的括号中

How to concatenate strings into parenthesis in Python

在 Python 我有这个循环,例如打印一些值:

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

现在一切正常,如果我打印 "toWrite",它会打印:

print toWrite

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

我的问题是,我如何将这些字符串与括号连接起来并用逗号分隔,所以循环的结果是这样的:

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

你会 group your items into pairs,然后使用字符串格式和 str.join():

','.join(['({},{})'.format(*pair) for pair in zip(*[iter(rows)] * 2)])
  • zip(*[iter(rows)] * 2) 表达式成对地生成来自 rows 的元素。
  • 每对的格式为'({},{})'.format(*pair)pair 中的两个值被放入每个 {} 占位符中。
  • (A,B) 个字符串使用 ','.join() 连接在一起成为一个长字符串。传入一个列表理解比在这里使用生成器表达式稍微快一些,因为 str.join() 否则会将它转换为列表 anyway 以便能够扫描它两次(一次用于输出大小计算,一次用于构建输出)。

演示:

>>> 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)'

试试这个:

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))))

这里采用了生成器和迭代器。 请参阅 itertools 以供参考。