Reputation: 13
I have to read a few user input parameters. Now I could do that for every single in a line e.g. parameter1=raw_input("Parameter 1:") parameter2=raw_input("Parameter 2:")
For better test purpose, it's more practical to do that in one line. For example: Input(parameters) could be: 1 both 0.5 2 5 0.8
So, is it possible to make 6 Parameters (some are int, some string and some float) out of this line?
B.t.w. I'm using python 2.7
Thanks for your help!
Upvotes: 1
Views: 2416
Reputation: 1
Had the question been in Python 3, here is the solution. Can't say if it will work in Python 2
What we do is make a list of the input and have it split on spaces. Then all we have to do is use the list
l=input().split(' ')
If instead of space, the separators were ',' we do the following and so on:
l=input().split(',')
Upvotes: 0
Reputation: 16711
Just split the contents by whitespace:
data = [int(i) for i in raw_input().split()] # cast to integers
Or you can alternatively use Python re:
data = [int(i) for i in re.findall(r'\d+', raw_input())]
Upvotes: 0
Reputation: 72
use regex for this case
import re
re_exp = re.compile(r'\s*(\d+)\s*([^\d\s])+\s*(\d+)')
expr = raw_input()
match = re_exp.match(expr)
if match:
num1, oper, num2 = match.groups()
print num1, oper, num2
It takes 3 inputs in one line (INT,OPERATION,INT). And prints it for you (int,operation,int) Work around it, to your need.
IDLE Output:
4 + 4 ( Three inputs)
4 + 4 (Prints them)
Upvotes: 0
Reputation: 1422
You can do as follow:
separator = ' '
parameters = raw_input("parameters:").split(separator)
parameters
will contain the list of the parameters given by the user.
separator
is the separator you want to use (a space in your example, but it could be any string)
Upvotes: 2