Convert String to tuple Python | Example code

There are 2 ways to convert Strings into tuple in Python. First, use parentheses to convert a string to a tuple without splitting or built-in function tuple() converts any sequence object to a tuple.

Convert String to tuple Python example

Simple example code.

Using parentheses ()

Follow a string with a comma, and enclose this in parentheses it will create a tuple containing the whole string as one element.

str1 = "Hello"

a_tuple = (str1,)

print(a_tuple)
print(type(a_tuple))

Output:

String to tuple Python

Using function tuple()

In this example, each character is treated as a string and inserted in a tuple separated by commas.

str1 = "Hello"

a_tuple = tuple(str1)

print(a_tuple)

Output: (‘H’, ‘e’, ‘l’, ‘l’, ‘o’)

Using eval() function

This converts the string to the desired tuple internally.

str1 = "1, -5, 4, 6, 7"

a_tuple = eval(str1)


print(a_tuple)

Output:

(1, -5, 4, 6, 7)

Do comment if you have any doubts and suggestions on this Python String tuple topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

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