0

In Python I have this loop that e.g. 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
Rodia
  • 1,407
  • 8
  • 22
  • 29
DaniKR
  • 2,418
  • 10
  • 39
  • 48

2 Answers2

2

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)'
Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

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.

crsxl
  • 185
  • 9