
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)
print(t)
# ('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:
print(i)
print('---')
# 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)
print(t)
# ('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)
print(x)
# ('A', 'B', 'C', 'D', 'E', 'F')
print(s)
# ABCDEF
Comments
Powered by Markdown