How to convert one str element from tuple to int value?
Question:
I have a tuple contains name, symbol, and number,
for example:
('albus dumbledore', '>', '3')
and I was trying to compare the number and other integer value from a list and I got an error message said ‘>’ not supported between instances of ‘int’ and ‘str’.
So I think I think I need to change the number value from the tuple from str to int like the below
('albus Dumbledore, '>', 3)
how do I convert the value?
Answers:
Once a tuple is created, you cannot change its values. You must first convert it into a regular list with list()
, change its values, then convert it back to a tuple with tuple()
. In order to convert a string into an integer, you can try to use int()
, then ignore the items that cannot be converted into an integer:
tuple_list = ('albus dumbledore', '>', '3')
tuple_list_modified = list(tuple_list)
for i in range(len(tuple_list_modified)):
try:
tuple_list_modified[i] = int(tuple_list_modified[i])
except ValueError:
continue
tuple_list = tuple(tuple_list_modified)
print(tuple_list)
Output:
('albus dumbledore', '>', 3)
I have a tuple contains name, symbol, and number,
for example:
('albus dumbledore', '>', '3')
and I was trying to compare the number and other integer value from a list and I got an error message said ‘>’ not supported between instances of ‘int’ and ‘str’.
So I think I think I need to change the number value from the tuple from str to int like the below
('albus Dumbledore, '>', 3)
how do I convert the value?
Once a tuple is created, you cannot change its values. You must first convert it into a regular list with list()
, change its values, then convert it back to a tuple with tuple()
. In order to convert a string into an integer, you can try to use int()
, then ignore the items that cannot be converted into an integer:
tuple_list = ('albus dumbledore', '>', '3')
tuple_list_modified = list(tuple_list)
for i in range(len(tuple_list_modified)):
try:
tuple_list_modified[i] = int(tuple_list_modified[i])
except ValueError:
continue
tuple_list = tuple(tuple_list_modified)
print(tuple_list)
Output:
('albus dumbledore', '>', 3)