Convert string to tuple in Python

You can convert a Python string to a tuple using tuple(), a Python built-in function.

s = 'Apple'

t = tuple(s)

# ('A', 'p', 'p', 'l', 'e')

A string is split into letters as a tuple. Each letter is an element of the tuple. If you only want to iterate all letters of a string, you don't need to convert it. Just iterate it in the if statement.

s = 'Word'

for i in s:

# W
# ---
# o
# ---
# r
# ---
# d
# ---

You can't convert int to tuple with tuple()

An int value can't be converted to a tuple as follows.

s = 123

t = tuple(s)

# TypeError: 'int' object is not iterable

It's possible to convert a f-string to a tuple.

x = 'ABC'
s = f'{x}DEF'

t = tuple(s)

# ('A', 'B', 'C', 'D', 'E', 'F')

Convert tuple to string

str() is not a function to convert a tuple to a string. It simply returns the tuple as string. It's so common to use join() for concatenating elements with a particular delimiter in this case.

t = ('A', 'B', 'C', 'D', 'E', 'F')

x = str(t)
s = ''.join(t)

# ('A', 'B', 'C', 'D', 'E', 'F')


Python String

Python Tutorial