How can you convert a tuple to a string in Python?

In Python, you can use the join function and map function to convert a tuple into a string.

Assuming there is a tuple t = (1, 2, 3, 4, 5), you can use the join function to concatenate the elements in the tuple into a string.

The example code is shown below:

t = (1, 2, 3, 4, 5)
s = ''.join(map(str, t))
print(s)

The running results:

12345

In the code above, the map function converts each element in the tuple to a string, then the join function connects these strings together and stores them in the variable s.

If you want to add a specific separator between each element, you can pass the separator as a parameter in the join function.

The sample code is given below:

t = (1, 2, 3, 4, 5)
s = '-'.join(map(str, t))
print(s)

Result of execution:

1-2-3-4-5

In the code above, set the delimiter for joining elements to ‘-‘ and use the join function to connect the elements in a tuple into a single string, with ‘-‘ added between each element.

bannerAds