Python - Convert Tuple String to Integer Tuple
Last Updated :
17 Apr, 2023
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))
OutputOriginal 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))
Method: Using enumerate function
Python3
tuple1 = ('1', '4', '3', '6', '7')
x=[int(i) for a,i in enumerate(tuple1)]
print(tuple(x))
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))
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))
OutputThe 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)
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.
OutputThe 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.
OutputThe 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 Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read