In this post, you will learn how to convert a tuple to a string in Python as well as we have three ways to convert that can very help full to you. In Python, you can store the multiple items in just a single variable as much as you want.
Contents
Convert Tuple To String In Python
Let’s get started
Use str.join() function
In Python, the first & very simple method to convert is str.join() function. It generates a string by concatenating the strings in a tuple. It returns strings that contain all the elements of the sequence joined by a string separator.
In the below code, we create a tuple list and use the join() to add all the characters in the input tuple and then convert it to string. After that use the str.join() function to convert a tuple into a string.
tup1 = ('w','h','o','l','e') # Use str.join() to convert tuple to string. str = ''.join(tup1) print (str)
Output:
whole
Using For Loop
First of all, create an empty string using for loop iterate then through the elements of the tuple. Keep it up adding each element to the empty string. It’s one of the simplest and easiest way, By using the way, the tuple value is converted to a string.
# into a string using a for loop def convertTuple(tup): # initialize an empty string str = '' for wholeblogs in tup: str = str + wholeblogs return str # Driver code tuple = ('w', 'h', 'o', 'l', 'e') str = convertTuple(tuple) print(str)
Output:
whole
Using reduce() function
You can use reduce() function to apply a particular function passed in it’s argument. To all of the list elements mentioned. Now we are passing the add operator in the functions to concatenate the characters of the tuple.
Process to use reduce() function
- First, import functools as well as import operator.
- Made function.
- After that make a tuple list.
- Make the second variable to convert & just print().
# into a string using reduce() function import functools import operator def convertTuple(tup): str = functools.reduce(operator.add, (tup)) return str # Driver code tuple = ('W', 'h', 'o', 'l', 'e') str = convertTuple(tuple) print(str)
Output:
whole
Using str.join() and map() function
Above we show that the str.join() function works well Here we are talking about only string objects as the tuple elements.
Note: If the tuple contains comes at least one non-string object then str.join() function will be failed & show TypeError as a String object cannot be added to a non-string object.
To avoid this error we have to use the map() function inside the join(). The map() function will take the iterator of the tuple and str() function such as its parameters.
let’s see the code & output
# into a string using str.join() & map() functions def convertTuple(tup): st = ''.join(map(str, tup)) return st # Driver code tuple = ('w', 'h', 'o', 'l', 'e ', 5) str = convertTuple(tuple) print(str)
Output:
whole 5
Read More: How to Convert C++ to Python