为了学习,有没有更短的方法:
if string.isdigit() == False :
我试过了:
if !string.isdigit() :
两者if !(string.isdigit()) :
都不起作用。
为了学习,有没有更短的方法:
if string.isdigit() == False :
我试过了:
if !string.isdigit() :
两者if !(string.isdigit()) :
都不起作用。
Python 的“非”操作数是not
, not !
。
Python 的“逻辑非”操作数是not
, not !
。
在 python 中,您使用not
关键字而不是!
:
if not string.isdigit():
do_stuff()
这相当于:
if not False:
do_stuff()
IE:
if True:
do_stuff()
此外,来自PEP 8 风格指南:
不要使用 == 将布尔值与 True 或 False 进行比较。
是:如果打招呼:
否:如果问候 == True
更糟糕的是:如果问候语为真:
if not my_str.isdigit()
另外,不要string
用作变量名,因为它也是广泛使用的标准模块的名称。
也许使用.isalpha()是一种更简单的方法......
所以; 而不是if not my_str.isdigit()
你可以尝试if my_str.isalpha()
这是检查字符串是否不是数字的较短方法
string.isdigit(g) 如果 g 为负数或浮点数,则返回 False。我更喜欢使用以下功能:
def is_digit(g):
try:
float(g)
except ValueError:
return False
return True