How to Convert Tuple to String in Python

Here are five ways to convert a tuple to a string in Python:

  1. Using the “string.join()”
  2. Using “for loop”
  3. Using “string.join()” function and “map()”
  4. Using the “functools.reduce()”
  5. Using a “list comprehension + join()”

Method 1: Using the join() function

An efficient way to convert a tuple to a string in Python is to use the “string.join()” method. The string join() is a built-in function that returns the string concatenated with an iterable element.

tup = ('G', 'R', 'O', 'G', 'U')

# Tuple to string
str = ''.join(tup)

print(str)

Output

GROGU

Method 2: Using For loop

Python for loop to iterate over the tuple’s elements and append them to a String. It takes a tuple and an empty string and uses the for loop to append one-by-one elements to a string.

tup = ('G', 'R', 'O', 'G', 'U')

str = ''

for item in tup:
  str = str + item

print(str)

Output

GROGU

This approach is not recommended because it takes an iteration, which is time-consuming. If you have big data then this approach is not feasible.

Method 3: Using string.join() function and map() function

def convertTuple(tup):
  s = ''.join(map(str, tup))
  return s


tuple = ('h', 'o', 'm', 'e', 'r', 404)
str = convertTuple(tuple)
print(str)

Output

homer404

Method 4: 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.

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)

Output

GROGU

Method 5: Using a list comprehension + join()

def convertTuple(tup):
  return ''.join([str(x) for x in tup])


# Driver code
tuple = ('h', 'o', 'm', 'e', 'r', 404)
str = convertTuple(tuple)
print(str)

Output

homer404

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.