简体   繁体   中英

how do I use .isalpha() to detect a maths operator

I'm trying to detect what math operator has been used and then assigning that operator to a variable. This is my code:

start = "3x - 2 = 11"
op = "+"

for m in start:
  if m.isalpha():
    if m == "-":
      op = m
    if m == "+":
      op = m
    if m == "*":
      op = m
    if m == "/":
      op = m
print(op)

However this prints "+", despite there being a "-" in the string start. Does anybody know why it is not printing out "-"? (btw this is python 3)

Under the assumption that there is a unique operator you could intersect the characters in start with the ops:

start = "3x - 2 = 11"
ops = set("+-*/")
op = list(set(start) & ops)[0] # op == '-'

If there are multiple operations in start then set(start) & ops would contain all of them (or be empty if there are no ops).

Note that in your example, you are implicitly using * since the intended meaning of 3x - 2 = 11 is probably 3*x - 2 = 11 .

The problem with your code is that, you're checking if the character is alphabet then do something, you can check if the character is not an alphabet or number.

op = "+"
for m in start:
  if not m.isalpha() and not m.isdigit():
    if m == "-":
      op = m
    if m == "+":
      op = m
    if m == "*":
      op = m
    if m == "/":
      op = m
    print op

OR you should rather keep an array of mathematical operators to check if the character is in your array

start = "3x - 2 = 11"
op = "+"
ops = ["-", "+", "/", "*"] #can be ("-", "+", "/", "*") or "-+/*" too
for m in start:
  if m in ops:
    if m == "-":
      op = m
    if m == "+":
      op = m
    if m == "*":
      op = m
    if m == "/":
      op = m
    print op

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM