在开始学习Python时,我在尝试使用Split进行计算时发现了一个问题。如果我的字符串中有白色的空间
15 - 3
然后该程序运行良好。
如果我的字符串中没有空格
15-3
然后,我会收到一个错误消息,因为拆分预期3个值(两个值和操作员(。我试图通过使用此方法来补偿它:
num1, operator, num2 = input("Enter calculation: ").split()
if not num1.isdigit() or not num2.isdigit():
print("Please use whitespaces in calculation")
else:
num1 = int(num1)
num2 = int(num2)
if operator == "+":
print("{} + {} = {}".format(num1, num2, num1+num2))
elif...
但是,如果我不使用空格,这仍然不会捕获错误。我在做什么错?
split
将字符串分开(默认情况下(,因此,如果用户未输入任何内容,则将字符串分为一个 part,并且可以
我将通过使用try...except
或首先存储整个输入并使用count
方法来检查用户实际上已输入所需的两个空格:
inp = input("Enter calculation: ")
if inp.count(" ") < 2:
print("Please use whitespaces in calculation")
else:
num1, operator, num2 = inp.split()
...
split
行可以提出ValueError: not enough values to unpack...
,因此,您的if
检查从未执行(它们是优秀的,太优势太过了(。
num1, operator, num2 = input("Enter calculation: ").split()
结果,您有2个选项:
在
split
ting之前检查传递的字符串:user_calc = input("Enter calculation: ") if ' ' not in user_calc: # do something about it
或将事物包裹在
try
-except
块中:try: num1, operator, num2 = input("Enter calculation: ").split() except ValueError: # do something about it
现在,在我看来,无论您选择哪种选项,您都必须将其包装在while
中,以使用户能够能力更正他的输入而无需再次运行代码。有关如何做到这一点的详细说明,请查看此出色的帖子
请注意,选项1.在您的情况下并不是最佳的,因为如果用户通过例如15 -2
,则if
不会触发,并且ValueError
提出。
,总而言之,我会这样做:
while True:
try:
num1, operator, num2 = input("Enter calculation: ").split()
except ValueError:
print('Spaces are needed between characters!')
else:
break
# rest of your code
这是一个想法:
import ast
str_input = input("Enter calculation: ")
print(ast.literal_eval(str_input))
您也可以使用正则言语,而忘记了空格
import re
num1, operator, num2 = re.split("([+-/*])", input("Enter calculation: ").replace(" ", ""))
print(eval(num1 + operator + num2))
否则,您可能只想防止任何间距更改输入。也就是说,使用re
。
import re
inp = input("Enter calculation: ") # collect input operation from user
inp = "".join(inp.split()) # remove all whitespaces
num1, operator, num2 = re.split("([+-/*])", inp) # split based on any operator in ['+', '-', '*', '/']
在这种情况下,您可以解析任何棘手的情况,例如:
* 1+ 12
* 2-5
* 1 * 5