Python 3.x 如何使用正则表达式从Python中的输入进行计算?
如何使用正则表达式从Python中的输入执行计算?输入的形式类似于字符串:Python 3.x 如何使用正则表达式从Python中的输入进行计算?,python-3.x,Python 3.x,如何使用正则表达式从Python中的输入执行计算?输入的形式类似于字符串: What is 1+1? 那么,如何从字符串中提取“1+1” 从输入字符串中提取表达式。最简单的方法是使用正则表达式: 求值表达式 (注意:eval是危险的,但是由于expr只有数值,所以可以使用它) 2.1。或者,您可以制作自己的计算器来计算表达式制作一个简短的程序: question = input("Please input and press enter: ") came_to_math = False a
What is 1+1?
那么,如何从字符串中提取“1+1”
eval
是危险的,但是由于expr
只有数值,所以可以使用它)
2.1。或者,您可以制作自己的计算器来计算表达式制作一个简短的程序:
question = input("Please input and press enter: ")
came_to_math = False
a=0
b=0
c=0
for e in question:
try:
int(e)
if came_to_math:
b=int(e)
break
else:
came_to_math = True
a=int(e)
except ValueError:
pass
if not came_to_math:
continue
try:
int(e)
except ValueError:
oparator = e
if oparator == "+":
print(a+b)
elif oparator == "-":
print(a-b)
elif oparator == "*":
print(a*b)
elif oparator == "/":
print(a/b)
else:
print("NOT SUPPORTED OPARATOR")
它只适用于0-9之间的数字!
你可以问这样的问题:
What is 1+2?
What is the result of 3+3?
What happens if I do: 7*5?
please calculate 5/4
到目前为止你试过什么?您希望支持哪些计算?你期望什么输入格式?
question = input("Please input and press enter: ")
came_to_math = False
a=0
b=0
c=0
for e in question:
try:
int(e)
if came_to_math:
b=int(e)
break
else:
came_to_math = True
a=int(e)
except ValueError:
pass
if not came_to_math:
continue
try:
int(e)
except ValueError:
oparator = e
if oparator == "+":
print(a+b)
elif oparator == "-":
print(a-b)
elif oparator == "*":
print(a*b)
elif oparator == "/":
print(a/b)
else:
print("NOT SUPPORTED OPARATOR")
What is 1+2?
What is the result of 3+3?
What happens if I do: 7*5?
please calculate 5/4