input 2 variables separated by a comma in a single line
Is it possible to input 2 numbers int
or float
separated by a comma in a single line?
Say after the program runs i开发者_运维知识库t would ask the user to Enter a range:
then the user would input 2,3
. So the variable range is [2,3]
. As far as I know range_choice.split()
is the only way.
num1,num2 = map(float, raw_input('Enter a range: ').split(','))
Alternatively, if you want to allow commas in the second value, use partition
instead of split
:
s1,_,s2 = raw_input('Enter a range: ').partition(',')
In this case, you'll have to convert the two strings to numbers by yourself.
num1, num2 = raw_input('Enter a range: ').split(',')
x,y = input("Enter range: ")
If you want them as numbers it's best not to use raw_input.
It's my understanding that ast.literal_eval
is safe:
>>> x, y = ast.literal_eval(raw_input('Enter a range: '))
Enter a range: 5, 6
>>> x, y
(5, 6)
In python3 you can directly use input() method instead of raw_input()
var1,var2 = input().split(',')
You can use:
for int
a,b = map(int,input().split(','))
or
a,b = [int(i) for i in input().split(',')]
for float
a,b = map(float,input().split(','))
Syntax:
var1 sep var2 sep ... sep varn = map(type, input().split('sep'))
or
var1 sep var2 sep ... sep varn = [type(var) for var in input().split('sep')]
for string
a, b = input().split(',')
精彩评论