1

If I have a list such as the following:

[(10, 20), (50, 60), (100, 110)]

How could I make this look like this:

'10-20,50-60,100-110'

if the number of pairs in my list is variable?

I am sorry for such an easy question. But every thing I have tried such as replacing the ',' with a '-' has failed. Any ideas?

jamylak
  • 128,818
  • 30
  • 231
  • 230
Peter Hanson
  • 193
  • 2
  • 11

4 Answers4

5
>>> x = [(10, 20), (50, 60), (100, 110)]
>>> ','.join('-'.join(map(str, t)) for t in x)
'10-20,50-60,100-110'
Dan D.
  • 73,243
  • 15
  • 104
  • 123
  • Could I do this 'string'+'|'+(','.join('-'.join(map(str, t)) for t in x)) and get string|10-20,50-60,100-110?? – Peter Hanson Apr 28 '12 at 01:50
  • 1
    @PatrickCampbell, Yes, you could also do `'string|%s' % ','.join('-'.join(map(str, t)) for t in x)` to avoid string concatentation. – huon Apr 28 '12 at 01:52
  • Could you help me with a similar question here please?! http://stackoverflow.com/questions/10359993/going-to-a-certain-position-in-a-string – Peter Hanson Apr 28 '12 at 02:34
2

Another (somewhat more readable) way to do this formatting is to use either

A) % style string formatting:

data = [(10, 20), (50, 60), (100, 110)]

fmt = "%d-%d, %d-%d, %d-%d" % (data[0][0], data[0][1], data[1][0], data[1][1],...)

or, with a list comprehension:

fmt = ",".join("%d-%d" % i for i in data)

B) The python string.format method:

fmt = ",".join("{0}-{1}".format(*i) for i in data)
Joel Cornett
  • 24,192
  • 9
  • 66
  • 88
1

Is this what your looking for?

data = [(10, 20), (50, 60), (100, 110)]
for x in data:
    print x[0], "-", x[1]
Lostsoul
  • 25,013
  • 48
  • 144
  • 239
  • Yes, something very close. However, I want to add that to a string I already have. So what would I do if I had string+????? – Peter Hanson Apr 28 '12 at 01:47
  • 1
    I'm not sure how your program is structured but instead of print you could append the result to your existing string? or if you merge later in your program you can make a list with the data being printed and then append it later on – Lostsoul Apr 28 '12 at 01:48
0

You can unpack the values of the list while iterating over it within a comprehension:

>>> x = [(10, 20), (50, 60), (100, 110)]
>>> ','.join('%d-%d' % (y,z) for (y,z) in x)
'10-20,50-60,100-110'
Jeff
  • 3,252
  • 3
  • 23
  • 13