How to Convert Python Tuple to String
Convert Python Tuple to String
To convert a tuple to string in Python, use one of the following methods.
Using String.join() method
Python string join() is an inbuilt function that returns the string concatenated with an iterable element. In this example, the iterable is a tuple, so that we will pass the tuple as an argument to the join() function, and it returns the string.
tup = ('G', 'R', 'O', 'G', 'U') # Tuple to string str = ''.join(tup) print(str)
The join() method appends all the tuple elements and creates a string from tuple elements.
Convert Tuple to String using For Loop
Python For Loop to iterate over the elements of the tuple and append them to a String. To convert a tuple to a string, take a tuple and empty string and use the for loop to append one by one element to a string.
tup = ('G', 'R', 'O', 'G', 'U') # empty string str = '' for item in tup: str = str + item print(str)
This approach is not recommended because it takes an iteration, which is time-consuming. If you have big data and then this approach is not feasible.
Using reduce() function to convert Tuple to String
The reduce() function is used to apply a specific function passed in its argument to all of the list elements mentioned in the sequence passed along. First, we need to import functools and operator modules.
See the following code.
import functools import operator def convert_str_to_tuple(tup): s = functools.reduce(operator.add, (tup)) return s tup = ('G', 'R', 'O', 'G', 'U') str = convert_str_to_tuple(tup) print(str)
Using the join() function is better than directly converting to a string using the str function. Also, if possible, don’t use for loop approach because it is time-consuming. That is it for converting tuple to string data type in Python.