Hi Guys, welcome to my blog in this article you will learn about how to Write A Python Program To Convert A Tuple Of String Values To A Tuple Of Integer Values
Title :
Write A Python Program To Convert A Tuple Of String Values To A Tuple Of Integer Values
Description :
Hey guys in this article you will learn how to convert the tuples of strings to tuples of integer values using the type conversion.
Ask the user to enter tuple length and iterate until tuple length, prompt the user to enter a number in string type.
Append each item to the tuple, and finally print the tuple.
length = int(input("Enter Tuple Length : "))
items = tuple()
for _ in range(length):
temp = input("Enter a Number : ")
items += (temp,)
print("Tuple of strings is : ", items)
Iterate all the items in tuple and convert each item into integers, if any exception occurs during the type conversion pass it.
numbers = tuple()
for item in items:
try:
numbers += (int(item),)
except Exception as e:
pass
Finally print the tuple containing integers using print function call
print("Converted Tuple of Integers is : ", numbers)
Complete Python Code :
length = int(input("Enter Tuple Length : "))
items = tuple()
for _ in range(length):
temp = input("Enter a Number : ")
items += (temp,)
print("Tuple of strings is : ", items)
numbers = tuple()
for item in items:
try:
numbers += (int(item),)
except Exception as e:
pass
print("Converted Tuple of Integers is : ", numbers)
Output :
Enter Tuple Length : 5
Enter a Number : 1
Enter a Number : 2
Enter a Number : e
Enter a Number : 3
Enter a Number : 4
Tuple of strings is : ('1', '2', 'e', '3', '4')
Converted Tuple of Integers is : (1, 2, 3, 4)
Output :
Enter Tuple Length : 4
Enter a Number : 1
Enter a Number : 2
Enter a Number : 3
Enter a Number : 900
Tuple of strings is : ('1', '2', '3', '900')
Converted Tuple of Integers is : (1, 2, 3, 900)
Conclusion :
The above Python program prompts the user to enter a tuple of string and then converts each item of tuple to integer.
It uses the type conversion to try and catch the exception, if any exception occurs during the conversion it passes it.
Comment it down below if you have any suggestions to improve the above Python program
0 Comments