This article will explain 3 different ways to convert a python tuple to string with example programs and explanation.
Python string class has a
join()
method which accepts an iterable as argument and returns a string which is a combination of items of the iterable.An iterable is anything than can be iterated or loop over such as a list, string or tuple. Example,
# create a tuple t = ('1','2','3','4','5') # convert to string s = ''.join(t) print('Tuple elements to string:',s)
which prints
Tuple elements to string: 12345
join()
method iterates over the tuple and combines them using the string on which it is called as a separator.
If you want the elements to be separated by some other separator, then invoke join()
using the separator as the string.
Thus, below statement will combine tuple elements with a dot in between
'.'.join(t)
Python
functools
module has a reduce()
function which accepts a sequence and a function as arguments and applies the function to the elements of the sequence and returns a single value.Thus, if we supply a function that accepts two parameters and returns the sum of these parameters as argument to
reduce()
, then we may combine the tuple elements into a single string as shown below.
import functools # function to add two values def add(v1, v2): return v1 + v2 t = ('1','2','3','4','5') s = functools.reduce(add, t) print('Tuple elements to string:', s)
Above code defines a function that adds two values and returns their sum. This function is supplied as the first argument to reduce()
.
Argument function to reduce()
can also be supplied as a lambda function as shown below.
s = functools.reduce(lambda x,y: x+y, t)
With above code, you do not need to define a separate function to add elements.
Python’s operator
module’s add()
function can also be supplied to reduce()
.
operator
module contains functions which are equivalent of mathematical operations and its add()
function signifies the addition operation.
Thus, reduce()
may also be written as
import operator s = functools.reduce(operator.add, t)
This is a fundamental approach where you iterate over a tuple and in every iteration add the current tuple element to a string. Example,
# define a tuple t = ('1','2','3','4','5') # define an empty string s = '' for e in t: # add tuple element s += e print('Tuple elements to string:', s)
This prints
Tuple elements to string: 12345
You may use any of the different methods to iterate the tuple.