1

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.

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Try this instead:

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

2 Comments

@IgnacioVazquez-Abrams there, fixed it.
The IndexError is gone, but this still won't do what the asker wants.
0

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.

1 Comment

yeah, i just realized that. thanks! It's just for me (the program) so I don't need to deal with lack of spaces.
0
#You should write like this
list1 = raw_input()
a=list1.split()
num1=a[0]
plus=a[1]
num2=a[2]
print num1, plus, num2

1 Comment

Hey, welcome to SO. Would be great if you could explain your code and give examples why op "should write like this".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.