Prince Ashitaka
Prince Ashitaka

Reputation: 8763

How to read two inputs separated by space in a single line?

I want to read two input values. First value should be an integer and the second value should be a float.

I saw Read two variables in a single line with Python, but it applies only if both the values are of same type. Do I have any other way?

Example input, first is int and second is float. The inputs should be on a single line:

20 150.50

http://www.codechef.com/problems/HS08TEST/

I'm very new to Python.

Upvotes: 21

Views: 146214

Answers (13)

Gamy Tuber
Gamy Tuber

Reputation: 1

In python 3 we can use,

r1,r2 = map(int,input().split(" "))

Upvotes: -1

Jasmohan
Jasmohan

Reputation: 237

In Python 2.7, I use this

A,B = raw_input().split(" ")
A = int(A)
B = float(B)
print(A)
print(B)

Output:

34 6.9

34

6.9

Upvotes: 3

Manan
Manan

Reputation: 1

Basically you just need to use map function and pass user define function for which datatype you need to convert.

code

You can even use it to convert it into other datatypes as well

Upvotes: -1

Shaila B
Shaila B

Reputation: 11

Below snippet works for me.

>>> a,b=list(map(int,input().split()))
1 2
>>> print(a)
1
>>> print(b)
2

Upvotes: 1

vijayraj34
vijayraj34

Reputation: 2415

Python 3.5

Below snippet works for me.

a, b = input().split(" ")
a_value = int(a)
b_value = int(b)

Upvotes: 0

Hafiz Mahdi Hasan
Hafiz Mahdi Hasan

Reputation: 1

Read 3 inputs separated by space...

arr = input().split(" ")
A = float(arr[0])
B = float(arr[1])
C = float(arr[2])
print(A)
print(B)
print(C)

Upvotes: 0

Maciej Bledkowski
Maciej Bledkowski

Reputation: 713

This is good solution imho a, b = input().split().

If you want to separate input with custom character you can put it in parenthesis e.g. a, b = input().split(",")

Upvotes: 0

sems
sems

Reputation: 21

If you wish to take as many inputs as u want then following:

    x=list(map(str,input().split())) 
    print(x)

If you want two inputs:

   x,y=x,y=list(map(str,input().split()))
   print(x,y)

Upvotes: 0

RITIK DWIVEDI
RITIK DWIVEDI

Reputation: 31

If the input is separated by spaces " "

a,b,c = raw_input().split(" ")

If the input is separated by comma ','

a,b,c = raw_input().split(",")

Upvotes: 3

Anonymous V
Anonymous V

Reputation: 31

map(str,input().split()) that is how you do it.

Upvotes: 2

Phoris
Phoris

Reputation: 41

Simpler one liner(but less secure):

map(eval, raw_input().split())

Upvotes: 4

snakehiss
snakehiss

Reputation: 8774

One liner :)

>>> [f(i) for f,i in zip((int, float), raw_input().split())]
1 1.2
[1, 1.2]

Upvotes: 4

Gabi Purcaru
Gabi Purcaru

Reputation: 31564

Like this:

In [20]: a,b = raw_input().split()
12 12.2

In [21]: a = int(a)
Out[21]: 12

In [22]: b = float(b)
Out[22]: 12.2

You can't do this in a one-liner (or at least not without some super duper extra hackz0r skills -- or semicolons), but python is not made for one-liners.

Upvotes: 31

Related Questions