Skip to content
Related Articles
Open in App
Not now

Related Articles

Python – Convert Tuple String to Integer Tuple

Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 23 Aug, 2022
Improve Article
Save Article

Interconversion of data is a popular problem developer generally deal with. One can face a problem to convert tuple string to integer tuple. Let’s discuss certain ways in which this task can be performed. 

Method #1 : Using tuple() + int() + replace() + split() The combination of above methods can be used to perform this task. In this, we perform the conversion using tuple() and int(). Extraction of elements is done by replace() and split(). 

Python3




# Python3 code to demonstrate working of
# Convert Tuple String to Integer Tuple
# Using tuple() + int() + replace() + split()
 
# initializing string
test_str = "(7, 8, 9)"
 
# printing original string
print("The original string is : " + test_str)
 
# Convert Tuple String to Integer Tuple
# Using tuple() + int() + replace() + split()
res = tuple(int(num) for num in test_str.replace('(', '').replace(')', '').replace('...', '').split(', '))
 
# printing result
print("The tuple after conversion is : " + str(res))

Output : 

The original string is : (7, 8, 9)
The tuple after conversion is : (7, 8, 9)

Method #2: Using eval() This is recommended method to solve this task. This performs the interconversion task internally. 

Python3




# Python3 code to demonstrate working of
# Convert Tuple String to Integer Tuple
# Using eval()
 
# initializing string
test_str = "(7, 8, 9)"
 
# printing original string
print("The original string is : " + test_str)
 
# Convert Tuple String to Integer Tuple
# Using eval()
res = eval(test_str)
 
# printing result
print("The tuple after conversion is : " + str(res))

Output : 

The original string is : (7, 8, 9)
The tuple after conversion is : (7, 8, 9)

Method #3: Using map()

Python3




test_tuple = ('1', '4', '3', '6', '7')
   
# Printing original tuple
print ("Original tuple is : " + str(test_tuple))
   
# using map() to
# perform conversion
test_tuple = tuple(map(int, test_tuple))
       
   
# Printing modified tuple
print ("Modified tuple is : " + str(test_tuple))

Output

Original tuple is : ('1', '4', '3', '6', '7')
Modified tuple is : (1, 4, 3, 6, 7)

Method: Using the list comprehension 

Python3




tuple1 = ('1', '4', '3', '6', '7')
x=[int(i) for i in tuple1]
print(tuple(x))

Output

(1, 4, 3, 6, 7)

Method: Using enumerate function 

Python3




tuple1 = ('1', '4', '3', '6', '7')
x=[int(i) for a,i in enumerate(tuple1)]
print(tuple(x))

Output

(1, 4, 3, 6, 7)

Method: Using lambda function

Python3




tuple1 = ('1', '4', '3', '6', '7')
x=[int(j) for j in (tuple(filter(lambda i:(i),tuple1)))]
print(tuple(x))

Output

(1, 4, 3, 6, 7)

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!