Python – Convert Tuple String to Integer Tuple

Interconversion of data is a popular problem developers 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().

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)) 

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)) 

chevron_right


Output :

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



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.