Skip to content

Convert String to tuple Python | Example code

  • by

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 or suggestions on this Python String tuple topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading