Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

See if *any* characters are in string and remove them

Tags:

python

string

So I have a simple program in Python 3 that is just a basic calculator. here is a section of code:

calculation = input("What calculation do you want to do?\n")
if "+" in calculation:
    numbers = calculation.split("+")
    answer = int(numbers[0]) + int(numbers[1])

I have some other operations setup below it. The issue is that if someone was to input anything as well as the operation (e.g. 10++2 or 10+abc2), the code throws back an error because it obviously can't add 10 to abc2.

I thought that I could solve the issue by testing for each individual character but surely that is a long way around the issue. Is there a way to solve the issue using Python?

like image 406
Soviet Ketchup Avatar asked Jan 28 '26 22:01

Soviet Ketchup


1 Answers

Check if both sides are made of digits by the string.isdigit() method:

if numbers[0].isdigit() and numbers[1].isdigit():
     answer = int(numbers[0]) + int(numbers[1])

If you want to go further with your calculator, you should worry about learning regex and parsing.

like image 69
Assem Avatar answered Jan 31 '26 22:01

Assem