Python program to convert tuple string to integer tuple

In this program, we have a tuple in string form. We need to create a Python program to convert this tuple String to the tuple.
Submitted by Shivang Yadav, on November 02, 2021

Sometimes, we come across situations where we have collections or structures encapsulated in a wrapper prior to transfer. In this article, we will see a program that will convert a string wrapped tuple to a tuple with integer values.

Input:
"(1, 5, 8)" 

Output:
(1, 5, 8)

Before going further with the problem, let's recap some basic topics that will help in understanding the solution.

Python programming language is a high-level and object-oriented programming language. Python is an easy to learn, powerful high-level programming language. It has a simple but effective approach to object-oriented programming.

Tuples in Python is a collection of items similar to list with the difference that it is ordered and immutable.

Example:

tuple = ("python", "includehelp", 43, 54.23)

Converting Tuple String to Integer Tuple

We have a string containing an integer-valued tuple inside it. And we need to convert this wrapped tuple to the integer tuple.
For performing this task, we will have multiple methods in the Python programming language.

Method 1:

To perform the conversion, we will use the method tuple() and int(), and to extract the elements from the string tuple, we will be using replace() and split() method.

# Python program to Convert Tuple String 
# to Integer Tuple

# Creating and Printing tuple string
tupleString = "(3, 7, 1, 9)"
print("The string tuple is : " + tupleString)

# Converting tuple string to integer tuple 
intTuple = tuple(int(ele) for ele in tupleString.replace('(', '').replace(')', '').replace('...', '').split(', '))

# Printing the converted integer tuple 
print("The integer Tuple is : " + str(intTuple))

Output:

The string tuple is : (3, 7, 1, 9)
The integer Tuple is : (3, 7, 1, 9)

Method 2:

Another method to solve the problem is using the eval() method which will directly perform the conversion internally.

# Python program to Convert Tuple String to 
# Integer Tuple using eval() method

# Creating and Printing tuple string
tupleString = "(3, 7, 1, 9)"
print("The string tuple is : " + tupleString)

# Converting tuple string to integer tuple 
intTuple = eval(tupleString)

# Printing the converted integer tuple 
print("The integer Tuple is : " + str(intTuple))

Output:

The string tuple is : (3, 7, 1, 9)
The integer Tuple is : (3, 7, 1, 9)

Python Tuple Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.