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

时间:2015-06-30 09:42:39

标签: python concatenation

在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

2 个答案:

答案 0 :(得分:2)

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()否则会将其转换为列表无论如何以便能够扫描它两次(一次用于输出大小计算,一次用于构建输出)。

演示:

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

答案 1 :(得分:1)

试试这个:

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以获取参考。