Python – Convert Tuple String to Integer Tuple
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 stringtest_str = "(7, 8, 9)"# printing original stringprint("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 resultprint("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 stringtest_str = "(7, 8, 9)"# printing original stringprint("The original string is : " + test_str)# Convert Tuple String to Integer Tuple# Using eval()res = eval(test_str)# printing resultprint("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 tupleprint ("Original tuple is : " + str(test_tuple)) # using map() to# perform conversiontest_tuple = tuple(map(int, test_tuple)) # Printing modified tupleprint ("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)






Please Login to comment...