Search code examples
pythonlisttuples

how to convert list of tuple into a string?


I have a list of tuple and I'd like to convert the list into a string of tuple pair separted by comman. Not sure how to do it?

For example if I have list of this

a=[(830.0, 930.0), (940.0, 1040.0)]

I'd like to convert it to a string like this

b="(830.0, 930.0), (940.0, 1040.0)"
a=[(830.0, 930.0), (940.0, 1040.0), (1050.0, 1150.0), (1160.0, 1260.0), (1270.0, 1370.0), (1380.0, 1480.0), (1490.0, 1590.0)]
b=','.join(a)
b
----> 2 b=','.join(a)
      3 b

TypeError: sequence item 0: expected str instance, tuple found

Solution

  • Use f-strings or formatted string literals and str.strip:

    a = [(830.0, 930.0), (940.0, 1040.0)]
    b = f"{a}".strip("[]")
    print(b)
    # (830.0, 930.0), (940.0, 1040.0)