Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何区分列表中的数字和符号?_Python_String_List_Python 3.x_Input - Fatal编程技术网

Python 如何区分列表中的数字和符号?

Python 如何区分列表中的数字和符号?,python,string,list,python-3.x,input,Python,String,List,Python 3.x,Input,我需要发出两条不同的错误消息:一条是用户输入数字,另一条是用户输入操作数(用于等式计算器)。 到目前为止,我的代码如下: #If user just presses enter: if len(theParts) == 0 : print("You have not entered an equation. Please, try again!") # If input is a word: elif equation.isalpha(): print("You have en

我需要发出两条不同的错误消息:一条是用户输入数字,另一条是用户输入操作数(用于等式计算器)。 到目前为止,我的代码如下:

#If user just presses enter:
if len(theParts) == 0 :
    print("You have not entered an equation. Please, try again!")

# If input is a word:
elif equation.isalpha():
    print("You have entered a word instead of an equation!")

elif len(theParts) == 1 :
    print("You have only entered an operand/operator. Please, try again!") 

elif len(theParts) == 2 :
    print("You have not entered a complete equation. Please, try again!")
我也尝试过使用equation.isnumeric(),但它也包含符号。是否有办法区分数字和符号,或者我是否必须对每个操作数执行类似的操作:

elif '*' in theParts and len(theParts) == 1:
    print("error")

我认为有两种方法可以做到这一点:

1.删除允许的非数字字符并使用。
“12345”.isdigit()#true
“123.45”。替换('.','').isdigit()#正确
“12*4.3”。isdigit()#false
2.定义您自己的允许字符集
def是一个好的数字:
对于s中的字符:
如果“1234567890”中没有字符:
返回错误
返回真值
你的号码(12345)正确吗
好的数字(“123.45”)是真的吗
好的数字(“12*4.3”)是假的吗

基本上,您需要创建令牌,然后分析这些令牌。编写解析器是一项艰巨的任务,因此我建议您研究类似pyparsing的东西来帮助您完成这项任务。我现在正在尝试
isnumeric()
,它不接受像
*
/
这样的符号,和
+
。您可以使用Tokenizers通读我的问题是,它也需要检测带小数的数字。一般来说,在我的代码中,如果用户只输入了一个符号,我会收到错误消息,但是如果他们输入了一个数字,他们会收到错误消息,说他们输入了一个符号。