Convert String to Tuple in Python

Here are the different ways to convert a string to a tuple in Python:

(1) String that contains integers separated by a delimiter (such as a comma):

my_string = "11,22,33,44,55"

my_tuple = tuple(my_string.split(","))

print(my_tuple)

The result is a tuple, where each element in the tuple is a string:

('11', '22', '33', '44', '55')

To convert the elements in the tuple to integers:

my_string = "11,22,33,44,55"

my_list = my_string.split(",")

my_tuple = tuple([int(i) for i in my_list])

print(my_tuple)

The elements in the tuple would now become integers:

(11, 22, 33, 44, 55)

(2) String that contains text separated by a delimiter (such as a comma):

my_string = "aa,bb,cc,dd,ee"

my_tuple = tuple(my_string.split(","))

print(my_tuple)

The result is a tuple with strings:

('aa', 'bb', 'cc', 'dd', 'ee')

(3) String that represents a tuple with integers:

my_string = "(11,22,33,44,55)"

my_tuple = eval(my_string)

print(my_tuple)

Or by:

import ast

my_string = "(11,22,33,44,55)"

my_tuple = ast.literal_eval(my_string)

print(my_tuple)

The result is a tuple with integers:

(11, 22, 33, 44, 55)

(4) String that represents a tuple with text elements:

my_string = "('aa','bb','cc','dd','ee')"

my_tuple = eval(my_string)

print(my_tuple)

Or by:

import ast

my_string = "('aa','bb','cc','dd','ee')"

my_tuple = ast.literal_eval(my_string)

print(my_tuple)

The result is a tuple with strings:

('aa', 'bb', 'cc', 'dd', 'ee')

Additional guides:

Leave a Comment