Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert elements(string) to integer in tuple in Python

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.

like image 859
harrisonthu Avatar asked Dec 09 '15 00:12

harrisonthu


People also ask

How will you convert a string to a tuple in Python?

When it is required to convert a string into a tuple, the 'map' method, the 'tuple' method, the 'int' method, and the 'split' method can be used. The map function applies a given function/operation to every item in an iterable (such as list, tuple). It returns a list as the result.

Can you convert a string to an integer in Python?

To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed.

How do you convert a list of elements to a tuple?

Using the tuple() built-in function An iterable can be passed as an input to the tuple () function, which will convert it to a tuple object. If you want to convert a Python list to a tuple, you can use the tuple() function to pass the full list as an argument, and it will return the tuple data type as an output.


1 Answers

You can use map.

myinput = "2 3"
mytuple = tuple(map(int, myinput.split(' ')))
like image 105
caiohamamura Avatar answered Oct 10 '22 12:10

caiohamamura