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

2024-09-19 23:43:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要生成两个不同的错误消息:一个是用户输入一个数字,一个是用户输入操作数(用于方程式计算器)。 目前我的代码如下:

#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!")

我也试过公式.isnumeric()但也包括符号。有没有办法区分数字和符号,或者我必须对每个操作数做如下操作:

^{pr2}$

Tags: 用户youanlenifhave数字print
1条回答
网友
1楼 · 发布于 2024-09-19 23:43:22

我有两种方法:

1。删除允许的非数字字符并使用^{}

"12345".isdigit()                   # true
"123.45".replace('.', '').isdigit() # true
"12*4.3".isdigit()                  # false

2。定义您自己的一组允许的字符

^{pr2}$

相关问题 更多 >