Newbie: How to convert a tuple of strings into a tuple of ints
Ben Finney
ben+python at benfinney.id.au
Wed Dec 30 17:57:22 EST 2015
otaksoftspamtrap at gmail.com writes:
> How do I get from here
>
> t = ('1024', '1280')
>
> to
>
> t = (1024, 1280)
Both of those are assignment statements, so I'm not sure what you mean
by “get from … to”. To translate one assignment statement to a different
assignment statement, re-write the statement.
But I think you want to produce a new sequence from an existing sequence.
The ‘map’ built-in function is useful for that::
sequence_of_numbers_as_text = ['1024', '1280']
sequence_of_integers = map(int, sequence_of_numbers_as_text)
That sequence can then be iterated.
Another (more broadly useful) way is to use a generator expression::
sequence_of_integers = (int(item) for item in sequence_of_numbers_as_text)
If you really want a tuple, just pass that sequence to the ‘tuple’
callable::
tuple_of_integers = tuple(
int(item) for item in sequence_of_numbers_as_text)
or::
tuple_of_integers = tuple(map(int, sequence_of_numbers_as_text))
--
\ “Nothing is more sacred than the facts.” —Sam Harris, _The End |
`\ of Faith_, 2004 |
_o__) |
Ben Finney
More information about the Python-list
mailing list