Write a Python Program to Convert a Tuple of String Values to a Tuple of Integer Values

Hi, in this blog lets look into how you can convert tuple of strings into tuple of integers using Python Programming Language.

I will be using the recursive function in order to convert the nested tuple in to another nested tuple.

 

 

Write a Python Program to Convert a Tuple of String Values to a Tuple of Integer Values

 

 

Lets write a function that takes input argument as tuple of strings and returns tuple of integer values. Inside the function lets use for loop to traverse each and every item of tuple. Check if the item is tuple call the function recursively and if the item is integer then convert the item to tuple of integer and add it to local tuple and return it.


Function to Convert a Tuple of String Values to a Tuple of Integer Values


def convert(my_tuple):
    local_tuple = tuple()
    
    for item in my_tuple:
        if isinstance(item, tuple):
            local_tuple += (convert(item),)
        elif isinstance(item, str):
            local_tuple += (int(item),)
    
    return local_tuple
    

In the Main Program lets take the tuple of string and pass it as input argument to the function.


data = ("23", ("33", "44"), ("14", "55"), ("1", "2", "3", ("11", "22")), ("4", "5", "6", "7"))
info = convert(data)
print("Tuple of string is : ")
print(data)
print("Tuple of integer is : ")
print(info)
 
 
OUTPUT : 
 
Tuple of string is : 
("23", ("33", "44"), ("14", "55"), ("1", "2", "3", ("11", "22")), ("4", "5", "6", "7"))
 
Tuple of integer is :  
(23, (33, 44), (14, 55), (1, 2, 3, (11, 22)), (4, 5, 6, 7))
 
 

Conclusion : Try to run all the program by yourself and comment down below if you have any issue.

 

 

Post a Comment

0 Comments