문제

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 ?

도움이 되었습니까?

해결책

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)'
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top