简体   繁体   中英

How to concatenate strings into parenthesis in Python

In Python I have this loop that eg prints some value:

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:

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

','.join(['({},{})'.format(*pair) for pair in zip(*[iter(rows)] * 2)])
  • The zip(*[iter(rows)] * 2) expression produces elements from rows in pairs.
  • Each pair is formatted with '({},{})'.format(*pair) ; the two values in pair are slotted into each {} placeholder.
  • The (A,B) strings are joined together into one long string using ','.join() . 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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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