Borislav Hadzhiev
Last updated: Jul 2, 2022
Photo from Unsplash
To convert a tuple of strings to a tuple of integers:
int()
class.tuple()
class to convert the generator object to a tuple.tuple_of_strings = ('10', '20', '30', '40') tuple_of_integers = tuple(int(item) for item in tuple_of_strings) # 👇️ (10, 20, 30, 40) print(tuple_of_integers)
We used a generator expression to iterate over the tuple of strings.
On each iteration, we pass the tuple element to the int()
class to convert it
to an integer.
The int class returns an integer object constructed from the provided number or string argument.
Alternatively, you can use the map()
function.
To convert a tuple of strings to a tuple of integers:
int()
class to the map()
function.map()
function will pass each item of the tuple to the int()
class.tuple_of_strings = ('10', '20', '30', '40') tuple_of_integers = tuple(map(int, tuple_of_strings)) # 👇️ (10, 20, 30, 40) print(tuple_of_integers)
The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.
This approach is a bit more implicit than using a generator expression.
The map()
function returns a map
object, so we had to use the tuple()
class to convert the map
object to a tuple.
Since tuples cannot be changed, the only way to convert a tuple of strings to a tuple of integers is to create a new tuple that contains integer values.
Which approach you pick is a matter of personal preference. I'd go with the generator expression as I find it more direct and more explicit.