[英]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
您可以將項目成對分組 ,然后使用字符串格式和str.join()
:
','.join(['({},{})'.format(*pair) for pair in zip(*[iter(rows)] * 2)])
zip(*[iter(rows)] * 2)
表達式從成對的rows
中生成元素。 '({},{})'.format(*pair)
; pair
的兩個值插入到每個{}
占位符中。 ','.join()
將(A,B)
字符串連接在一起成為一個長字符串。 傳遞列表str.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)'
嘗試這個:
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以獲取參考。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.