Convert a Tuple to a String in Python [Step-by-Step]

Convert Tuple To String In Python

In this tutorial, we will discuss the different methods to convert a tuple to a string in Python.


What is a Tuple in Python?

In Python, a tuple is a linear data structure that is used to store an ordered collection of data that can either be of similar types or different types. The elements of a tuple are enclosed in the parentheses ().

All elements of a tuple are indexed from 0 to N-1 where N is the length or size of the tuple and we can directly access any element of a tuple.

It also allows duplicate values to be stored which means different indexed elements can have the same value.

A tuple is immutable in nature which means we cannot change its value after creating it.

Here is how we can create a tuple in Python. We’ll use the type() method to validate that a tuple has certainly been created.

# Defining a Python tuple
tp = ('Ubuntu', 'Kali', 'Debian', 'Fedora', 'Ubuntu')
 
# Printing the results
print(tp)
 
# Validating the type of 'tp'
print(type(tp))

Output:

('Ubuntu', 'Kali', 'Debian', 'Fedora', 'Ubuntu')
<class 'tuple'>

What is a string in Python?

In Python, a string is the most commonly used data type. Any value enclosed in single, double, or triple quotes is considered a string. Triple quotes also allow you to enter multiple lines into the string variable.

A Python string can be considered as an array of characters but please remember we don’t have any character data type in Python so even a single character is also a string.

Like Python tuple, all elements (characters) of a string are indexed from 0 to N-1 where N is the length or size of the string and we can directly access any character of a string.

A Python string is mutable which means we can change its value after creating it. We have one built-in function print() in Python which is used to print a string value on the console.

# Defining Python string
str1 = 'AskPython'
str2 = "LinuxforDevices"
str3 = """AskPython and LinuxforDevices 
are parts of JournalDev 
IT Services Private Limited."""

# Printing the results
print(str1)
print(str2)
print(str3)
 
# Validating the type of str1, str2, & str3
print(type(str1))
print(type(str2))
print(type(str3))

Output:

AskPython
LinuxforDevices
AskPython and LinuxforDevices  
are parts of JournalDev  
IT Services Private Limited. 
<class 'str'> 
<class 'str'> 
<class 'str'>

3 Ways to Convert a Tuple to a String

Mainly there are three methods to convert a tuple to a string in Python which are often used and important to understand. Let’s discuss them one by one.

Recommended read: Python astype() method

1. Convert a tuple to a string using for loop

In this method of converting a Python tuple to a Python string, we will use simple for loop to iterate through the tuple elements and keep on adding each element of the tuple to an empty Python string. Let’s understand this through the following Python code.

# Defining a Python tuple
tp = ('Linux', 'for', 'Devices')

# Creating an empty Python string
st = ''

# Using the Python for loop to convert the tuple to a string
for item in tp:
    st = st + item

# Printing the results
print("Given Python tuple: ", tp)
print("Generated Python string: ", st)

# Validating the type of 'st'
print(type(st))

Output:

Given Python tuple:  ('Linux', 'for', 'Devices') 
Generated Python string:  LinuxforDevices 
<class 'str'>

2. Convert a tuple to a string using Python join() function

In this method of converting a Python tuple to a Python string, we will use str.join() function. This Python function takes an iterable Python object like tuple as its argument and returns a Python string joined using a string separator or delimiter. This separator or delimiter can b

e any string but usually, we use an empty string (“”), comma (,), hyphen (-), and single space (” “). Let’s understand this through the following Python code.

# Defining a Python tuple
tp = ('AskPython', 'is', 'a', 'part', 'of', 'JournalDev.')

# Creating a string separator/delimiter
# Here it's a single space
st = ' '

# Using the Python str.join() function to convert the tuple to a string
st = st.join(tp)

# Printing the results
print("Given Python tuple: ", tp)
print("Generated Python string: ", st)

# Validating the type of 'st'
print(type(st))

Output:

Given Python tuple:  ('AskPython', 'is', 'a', 'part', 'of', 'JournalDev.') 
Generated Python string:  AskPython is a part of JournalDev. 
<class 'str'>

3. Convert a tuple to a string using Python reduce() function

In this method of converting a Python tuple to a Python string, we will use the reduce() function. In Python, the reduce() function takes a function as its first argument and an iterable like a tuple as its second argument.

Then it applies that function to each element of the iterable object and returns the final result of the operation performed by the function.

Here we will pass the add function and a tuple as the iterable object. In this way, the reduce() function will add each element of the tuple.

Let’s understand how to use this reduce() and add() functions to convert a tuple to a string through Python code.

NOTE: To use the reduce() and the add() functions, we have to import two Python modules funtools and operator. As the reduce() and the add() functions are defined in funtools and operator modules respectively. And we need not install these modules as they are the standard modules of Python and get installed on the system along with the Python Interpreter.

# Importing Python functools module which contains the reduce() function
import functools

# Importing Python operator module which contains the add() function
import operator

# Defining a Python tuple
tp = ('Linux', 'for', 'Devices')

# Using the Python  reduce() function to convert the tuple to a string
st = functools.reduce(operator.add, tp)
 
# Printing the results
print("Given Python tuple: ", tp)
print("Generated Python string: ", st)

# Validating the type of 'st'
print(type(st))

Output:

Given Python tuple:  ('Linux', 'for', 'Devices') 
Generated Python string:  LinuxforDevices 
<class 'str'>

Errors while using Python join() to convert tuple to a string

If we try to convert a tuple (with at least one non-string element) to a string in Python using join() function, then we may get an error.

This is actually a TypeError which is produced because the join() function cannot join or concatenate a string value with a non-string value.

Hence to overcome this TypeError we make use of the map() function. In Python, the map() function takes two arguments first one is a function and the second one is an iterable Python object like a tuple then it applies that function to each element of the iterable object.

And finally, it returns a map object which actually an iterator. This iterator is of the iterable whose elements are the results of the function applied on every element of the iterable object passed as an argument.

Let’s understand this concept through Python code.

# Defining a Python tuple with two non-string elements (float)
tp = ('Ubuntu', 'is', 'available', 'in', 'different', 'versions:', 20.04, 18.04, 'etc.')

# Creating a string separator/delimiter
# Here it's a single space
st = ' '

# Using the Python join() function to convert the tuple to a string
st = st.join(tp)

# Printing the results
print("Given Python tuple: ", tp)
print("Generated Python string: ", st)

# Validating the type of 'st'
print(type(st))

Output:

TypeError With Join convert tuple to a string
TypeError With str.join() function

Now let’s run the above Python program using the map() function with the join() function and see if this TypeError is removed or not.

# Defining a Python tuple with two non-string elements (float)
tp = ('Ubuntu', 'is', 'available', 'in', 'different', 'versions:', 20.04, 18.04, 'etc.')

# Creating a string separator/delimiter
# Here it's a single space
st = ' '

# Using the Python map() function with str.join() function to convert the tuple to a string
# Here the first argument is str() function & the second argument is a tuple
st = st.join(map(str, tp))

# Printing the results
print("Given Python tuple: ", tp)
print("Generated Python string: ", st)

# Validating the type of 'st'
print(type(st))

Output:

Given Python tuple:  ('Ubuntu', 'is', 'available', 'in', 'different', 'versions:', 20.04, 18.04, 'etc.') 
Generated Python string:  Ubuntu is available in different versions: 20.04 18.04 etc. 
<class 'str'>

Summing-up

In this tutorial, we have learned three different methods to convert a tuple to a string in Python. We have also learned about join() function, map() function, and reduce() function in Python. We have also learned to solve the TypeError that arises while using the str.join() function to convert a tuple to a string in Python.