How to convert elements(string) to integer in tuple in Python
Asked Answered
F

2

15

I am still learning Python and currently solving a question on Hackerrank where I am thinking of converting input(String type) to tuple by using built-in function(tuple(input.split(" ")).

For example, myinput = "2 3", and I want to convert it to tuple,such as (2,3). However,if I do that, it will, of course, give me a tuple with String type, like ('2', '3'). I know that there are a lot of ways to solve the problem, but I'd like to know how to convert elements(str) in tuple to integer(in Python) in most efficient way.

See below for more details.

>>> myinput = "2 3"
>>> temp = myinput.split()
>>> print(temp)
['2', '3']
>>> mytuple = tuple(myinput)
>>> print(mytuple)
('2', ' ', '3')
>>> mytuple = tuple(myinput.split(" "))
>>> mytuple
('2', '3')
>>> type(mytuple)
<class 'tuple'>
>>> type(mytuple[0])
<class 'str'>
>>> 

Thanks in advance.

Fantail answered 9/12, 2015 at 0:38 Comment(2)
Use map.Labourite
a trivial generator comprehension + tuple will do. (but map is in fact a little shorter)Jaret
L
38

You can use map.

myinput = "2 3"
mytuple = tuple(map(int, myinput.split(' ')))
Labourite answered 9/12, 2015 at 0:49 Comment(0)
B
3

This seems to be a more readable way to convert a string to a tuple of integers. We use list comprehension.

myinput = "2 3 4"
mytuple = tuple(int(el) for el in myinput.split(' '))
Boyne answered 1/12, 2019 at 14:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.