Python | Program to convert a tuple to a string
Given a tuple of characters, Write a python program to convert the tuple into a string.
Examples:
Input : ('a', 'b', 'c', 'd', 'e') Output : abcde Input : ('g', 'e', 'e', 'k', 's') Output : geeks
Approach
There are various approaches to convert a tuple to a string.
- Approach 1 : using str.join()
The join() method is a string method and returns a string in which the elements of sequence have been joined by str separator.
Using join() we add the characters of the tuple and convert it into string.# Python3 code to convert tuple
# into string
def
convertTuple(tup):
str
=
''.join(tup)
return
str
# Driver code
tuple
=
(
'g'
,
'e'
,
'e'
,
'k'
,
's'
)
str
=
convertTuple(
tuple
)
print
(
str
)
Output:
geeks
- Approach 2 : using reduce() function
The reduce(fun, seq) function is used to apply a particular function passed in its argument to all of the list elements mentioned in the sequence passed along. We pass the add operator in the function to concatenate the characters of tuple.# Python3 code to convert tuple
# into string
import
functools
import
operator
def
convertTuple(tup):
str
=
functools.
reduce
(operator.add, (tup))
return
str
# Driver code
tuple
=
(
'g'
,
'e'
,
'e'
,
'k'
,
's'
)
str
=
convertTuple(
tuple
)
print
(
str
)
Output:geeks
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.