A tuple is a collection of objects that are ordered and immutable. Tuples are sequences; just like lists, string represents the arrays of bytes representing the Unicode characters.
Python tuple to string
To convert a tuple to a string in Python, use the string.join() method. The string join() is a built-in function that returns the string concatenated with an iterable element.
In this example, the iterable is a tuple, so we will pass the tuple as an argument to the join() function, which 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 tuple’s elements 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 functools.reduce() function
The functools.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.