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)) |
The original string is : (7, 8, 9) The tuple after conversion is : (7, 8, 9)
Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(n), as we are creating a new tuple with the same number of elements as the input string.
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)) |
The original string is : (7, 8, 9) The tuple after conversion is : (7, 8, 9)
Time Complexity: O(n)
Auxiliary Space: O(1)
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)) |
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)) |
(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)) |
(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)) |
(1, 4, 3, 6, 7)
Method: Using ast
Python3
import ast # initializing string test_str = "(7, 8, 9)" # printing original string print ( "The original string is : " + test_str) # Convert Tuple String to Integer Tuple res = ast.literal_eval(test_str) # printing result print ( "The tuple after conversion is : " + str (res)) |
The original string is : (7, 8, 9) The tuple after conversion is : (7, 8, 9)
Time complexity: The time complexity of this code is O(1) because the string length is fixed and does not depend on the input size.
Auxiliary space complexity: The space complexity of this code is O(1) because the input and output are stored in constant space, and the ast module does not use any significant extra memory.
Method: Using for loop and append
Python3
tuple_string = "(1, 2, 3, 4)" int_tuple = [] for x in tuple_string[ 1 : - 1 ].split( "," ): int_tuple.append( int (x)) int_tuple = tuple (int_tuple) print (int_tuple) # Output: (1, 2, 3, 4) |
(1, 2, 3, 4)
The ast module provides the literal_eval function which evaluates a string containing a literal value and returns the value. In this case, we can pass in the string representation of a tuple, and literal_eval will return the actual tuple.
Time complexity: O(n), where n is the length of the input string.
Auxiliary Space: O(n), where n is the length of the input string.
Method : Using a for loop
In this code, we iterate through each character in the input string. If the character is a digit, we add it to a temporary string. When we encounter a non-digit character, we check if the temporary string has any digits in it. If it does, we convert the temporary string to an integer and add it to the result list. Finally, we convert the result list to a tuple and print it.
Python3
test_str = "(7, 8, 9)" res = [] temp = '' for char in test_str: if char.isdigit(): temp + = char elif temp: res.append( int (temp)) temp = '' if temp: res.append( int (temp)) res = tuple (res) print ( "The tuple after conversion is : " + str (res)) #This code is contributed by Vinay Pinjala. |
The tuple after conversion is : (7, 8, 9)
Time complexity: The time complexity of the for loop method is O(n), where n is the length of the input string. This is because the for loop iterates through each character of the string only once and performs a constant number of operations for each character.
Method: Using Recursive method.
Auxiliary Space: The space complexity of the for loop method is O(n), where n is the length of the input string. This is because the method creates a list to store the integer values extracted from the string, and the size of this list is proportional to the length of the string.
Algorithm:
- Define a helper function to recursively process the string and build the tuple.
- The helper function takes two arguments: the current index in the string, and a temporary string to store digits.
- The helper function checks if the current character at the given index is a digit.
- If it is a digit, it is added to the temporary string and the helper function is called again with the next index and the updated temporary string.
- If it is not a digit, the temporary string is converted to an integer and appended to the result list.
- Finally, the helper function returns the result tuple.
- The main function calls the helper function with the initial index and an empty temporary string.
- The main function returns the result tuple.
Python3
def str_to_tuple(test_str): def helper(index, temp): if index > = len (test_str): if temp: res.append( int (temp)) return tuple (res) elif test_str[index].isdigit(): temp + = test_str[index] return helper(index + 1 , temp) elif temp: res.append( int (temp)) temp = '' return helper(index + 1 , temp) res = [] return helper( 0 , '') test_str = "(7, 8, 9)" res = str_to_tuple(test_str) print ( "The tuple after conversion is : " + str (res)) #This code is contributed by tvsk. |
The tuple after conversion is : (7, 8, 9)
The time complexity of this algorithm is O(n), where n is the length of the input string. This is because each character in the string is visited exactly once.
The space complexity is also O(n), as the result list may contain n elements at most. However, in practice, the space complexity is likely to be much smaller as most tuples are likely to contain only a few elements.
Method: Using numpy package
Note: first install numpy package by using : pip install numpy
- Importing the numpy package
- Using the astype() in numpy array to convert each element integer using np.array()
- Converting the numpy array to tuple
- Printing the result
Python3
# importing numpy library import numpy as np # initializing tuple string test_tuple = ( '1' , '4' , '3' , '6' , '7' ) # Printing original tuple print ( "Original tuple is : " + str (test_tuple)) # using astype() method of numpy array to convert each string element to integer test_tuple = np.array(test_tuple).astype( int ) # converting numpy array to tuple test_tuple = tuple (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)
Time Complexity: O(N) as we have to traverse the whole tuple of length N
Auxiliary Space: O(N) as we are creating array of length N.