1

At some point in my code, i have a list of tuples that i need to pass as a string, but a string that includes the structural elements of the tuple ie comas and parenthesis.

Currently i'm doing this :

   listofv = ''
   for tu in listof2tuple:
        ltu = '(' + tu[0] + ',' + tu[1] + ')'
        listofv.append(ltu)
   finalstring = ','.join(listofv)

While this works it seems strange, since printing the tuple in IDLE shows a string that is exactly what i want already.

What's the good way of doing this ?

zlr
  • 789
  • 11
  • 22
  • What about calling `repr()` on it then? Also, why are you passing it as a string? It seems strange. – FatalError Apr 07 '14 at 15:38
  • yes, repr() will do it ! the finalstring is used in a HTTP POST with a drastic syntax and i think it seems better to offload the construction of the argument list from the http call itself. – zlr Apr 07 '14 at 15:49

1 Answers1

5

Use repr:

>>> LoT
[(1, 2), (3, 4), (5, 6)]
>>> repr(LoT)
'[(1, 2), (3, 4), (5, 6)]'

Your code does not add the [..] braces for the list. If you do not want the list braces you can strip those off:

>>> repr(LoT).strip('[]')
'(1, 2), (3, 4), (5, 6)'
dawg
  • 98,345
  • 23
  • 131
  • 206
  • Curious. Why use `repr()` and not `str()`? – cdarke Apr 07 '14 at 15:46
  • I cannot say better than [this](http://stackoverflow.com/a/2626364/298607) great SO answer. `str()` would also work; `repr()` is less ambiguous of a result. *Usually* python simple data structures can be reconstituted (using ast.literal_eval) into their original form if `repr()` was used to create the string. – dawg Apr 07 '14 at 15:48
  • thanks, I'm familiar with the link you gave, and often there is no difference. – cdarke Apr 07 '14 at 15:54