AppDividend
Latest Code Tutorials

How to Convert Python Tuple to String

0

A tuple is a collection of objects that are ordered and immutable. Tuples are sequences, just like lists. Python string represents the arrays of bytes representing the Unicode characters.

Convert Python Tuple to String

To convert a tuple to string in Python, use one of the following methods.

  1. String.join() method
  2. Using functools.reduce() method

Using String.join() method

Python string join() is an inbuilt function that returns the string concatenated with an iterable element. In this example, the iterable is a tuple, so that we will pass the tuple as an argument to the join() function, and it returns the string.

Syntax

''.join(tuple)

Example

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

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

print(str)

Output

GROGU

The join() method appends all the tuple elements and creates a string from tuple elements.

Convert Tuple to String using For Loop

Python For Loop to iterate over the elements of the tuple and append them to a String. To convert a tuple to a string, take a tuple and empty string and use the for loop to append one by one element to a string.

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

# empty string
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 and then this approach is not feasible.

Using reduce() function to convert Tuple to String

The 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.

See the following code.

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

Conclusion

Using the join() function is better than directly converting to a string using the str function. Also, if possible, don’t use for loop approach because it is time-consuming. That is it for converting tuple to string data type in Python.

See also

Python tuple to array

Python tuple to dictionary

Python tuple to list

Leave A Reply

Your email address will not be published.

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