1

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!

David
  • 13
  • 3
  • possible duplicate of [How to input 2 integers in one line in Python?](http://stackoverflow.com/questions/23253863/how-to-input-2-integers-in-one-line-in-python) – Paul Feb 24 '15 at 11:04
  • The linked question shows how to split a line on whitespace. Is that enough to solve your problem, or do you need help converting the inputs to integers and floats? And if so, would it be OK if any numbers were simply all converted to floats? If not, how should the program decide which one to parse as integer and which as float? What should happen if user input doesn't match that? As you can see, we need a lot more information for a meaningful, nontrivial answer... – Tim Pietzcker Feb 24 '15 at 11:08

4 Answers4

2

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)

Tom Cornebize
  • 1,362
  • 15
  • 33
  • Thanks, very usefull. Comment: To use the parameters (maybe with print) you can use the []. E.g. print parameters[1] – David Feb 26 '15 at 08:01
0

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)

0

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())]
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70
0

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(',')