Open In App

Python – Convert Tuple String to Integer Tuple

Last Updated : 17 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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)

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


Output : 

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


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)

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


Output

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)


Output

(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.


Output

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:

  1. Define a helper function to recursively process the string and build the tuple.
  2. The helper function takes two arguments: the current index in the string, and a temporary string to store digits.
  3. The helper function checks if the current character at the given index is a digit.
  4. 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.
  5. If it is not a digit, the temporary string is converted to an integer and appended to the result list.
  6. Finally, the helper function returns the result tuple.
  7. The main function calls the helper function with the initial index and an empty temporary string.
  8. 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.


Output

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.



Similar Reads

Python | Convert Tuple to integer
Sometimes, while working with records, we can have a problem in which we need to convert the data records to integer by joining them. Let's discuss certain ways in which this task can be performed. Method #1 : Using reduce() + lambda The combination of above functions can be used to perform this task. In this, we use lambda function to perform logi
5 min read
Python - Convert Binary tuple to Integer
Given Binary Tuple representing binary representation of a number, convert to integer. Input : test_tup = (1, 1, 0) Output : 6 Explanation : 4 + 2 = 6. Input : test_tup = (1, 1, 1) Output : 7 Explanation : 4 + 2 + 1 = 7. Method #1 : Using join() + list comprehension + int() In this, we concatenate the binary tuples in string format using join() and
5 min read
Python - Convert Tuple to Tuple Pair
Sometimes, while working with Python Tuple records, we can have a problem in which we need to convert Single tuple with 3 elements to pair of dual tuple. This is quite a peculiar problem but can have problems in day-day programming and competitive programming. Let's discuss certain ways in which this task can be performed. Input : test_tuple = ('A'
10 min read
Python Program to Convert Tuple Matrix to Tuple List
Given a Tuple Matrix, flatten to tuple list with each tuple representing each column. Example: Input : test_list = [[(4, 5), (7, 8)], [(10, 13), (18, 17)]] Output : [(4, 7, 10, 18), (5, 8, 13, 17)] Explanation : All column number elements contained together. Input : test_list = [[(4, 5)], [(10, 13)]] Output : [(4, 10), (5, 13)] Explanation : All co
8 min read
Python program to convert Set into Tuple and Tuple into Set
Let's see how to convert the set into tuple and tuple into the set. For performing the task we are use some methods like tuple(), set(), type(). tuple(): tuple method is used to convert into a tuple. This method accepts other type values as an argument and returns a tuple type value.set(): set method is to convert other type values to set this meth
7 min read
Python | Convert list of string into sorted list of integer
Given a list of string, write a Python program to convert it into sorted list of integer. Examples: Input: ['21', '1', '131', '12', '15'] Output: [1, 12, 15, 21, 131] Input: ['11', '1', '58', '15', '0'] Output: [0, 1, 11, 15, 58] Let's discuss different methods we can achieve this task. Method #1: Using map and sorted() C/C++ Code # Python code to
4 min read
Python - Convert Alternate String Character to Integer
Interconversion between data types is facilitated by python libraries quite easily. But the problem of converting the alternate list of string to integers is quite common in development domain. Let’s discuss few ways to solve this particular problem. Method #1 : Naive Method This is most generic method that strikes any programmer while performing t
5 min read
Convert integer to string in Python
In Python an integer can be converted into a string using the built-in str() function. The str() function takes in any python data type and converts it into a string. But use of the str() is not the only way to do so. This type of conversion can also be done using the "%s" keyword, the .format function or using f-string function. Below is the list
3 min read
How to convert string to integer in Python?
In Python, a string can be converted into an integer using the following methods : Method 1: Using built-in int() function: If your string contains a decimal integer and you wish to convert it into an int, in that case, pass your string to int() function and it will convert your string into an equivalent decimal integer. Syntax : int(string, base)
3 min read
Python - Convert Integer Matrix to String Matrix
Given a matrix with integer values, convert each element to String. Input : test_list = [[4, 5, 7], [10, 8, 3], [19, 4, 6]] Output : [['4', '5', '7'], ['10', '8', '3'], ['19', '4', '6']] Explanation : All elements of Matrix converted to Strings. Input : test_list = [[4, 5, 7], [10, 8, 3]] Output : [['4', '5', '7'], ['10', '8', '3']] Explanation : A
6 min read
Practice Tags :
three90RightbarBannerImg