Maddy Byahoo
Maddy Byahoo

Reputation: 151

Multiple variables from single line in Python?

I'm trying to figure out how have something like "Enter an expression: " take in 3 variables: the first int, the character of the operation, and the second int. This is very easy in C++ with just cin >> num1 >> operation >> num2.

So far, per others' questions, I've tried taking in a list and splitting it. This works, except for integers with more than 1 digit. I'm doing something like this:

list1=raw_input()
list1.split()
print list1
num1=list1[0]
plus=list1[1]
num2=list1[2]
print num1, plus, num2

For example, entering 10+3 would output 1 0 + I feel like there's a simple fix here, but I don't know it. Any help is appreciated.

Upvotes: 1

Views: 3977

Answers (4)

SACHIN TIWARI
SACHIN TIWARI

Reputation: 1

#You should write like this
list1 = raw_input()
a=list1.split()
num1=a[0]
plus=a[1]
num2=a[2]
print num1, plus, num2

Upvotes: 0

bereal
bereal

Reputation: 34302

I'd suggest using regex for this case, for example:

 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

With split, you can parse 10 + 1 but it will be harder to do with 10+1 (without spaces), or to handle both cases.

Upvotes: 0

Óscar López
Óscar López

Reputation: 236112

Try this instead:

list1 = raw_input()
for x in list1.split():
    print x,

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799290

Strings are immutable, so you need to capture the result of list1.split() somewhere. But it won't help you, since that won't do what you want. Use a parser, possibly using Python's language services.

Upvotes: 1

Related Questions