Python 检查字符串是否不是 isdigit() 的更短方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16335771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Shorter way to check if a string is not isdigit()
提问by Nick Rutten
For the sake of learning, is there a shorter way to do:
if string.isdigit() == False :
为了学习,有没有更短的方法:
if string.isdigit() == False :
I tried:
if !string.isdigit() :and if !(string.isdigit()) :which both didn't work.
我想:
if !string.isdigit() :和if !(string.isdigit()) :这两人都没有工作。
采纳答案by Meoiswa
Python's "not" operand is not, not !.
Python 的“非”操作数是not, not !。
Python's "logical not" operand is not, not !.
Python 的“逻辑非”操作数是not, not !。
回答by Volatility
if not my_str.isdigit()
Also, don't use stringas a variable name as it is also the name of a widely used standard module.
另外,不要string用作变量名,因为它也是广泛使用的标准模块的名称。
回答by TerryA
In python, you use the notkeyword instead of !:
在python中,您使用not关键字而不是!:
if not string.isdigit():
do_stuff()
This is equivalent to:
这相当于:
if not False:
do_stuff()
i.e:
IE:
if True:
do_stuff()
Also, from the PEP 8 Style Guide:
此外,来自PEP 8 风格指南:
Don't compare boolean values to True or False using ==.
Yes: if greeting:
No: if greeting == True
Worse: if greeting is True:
不要使用 == 将布尔值与 True 或 False 进行比较。
是:如果问候:
否:如果问候 == 真
更糟糕的是:如果问候是真的:
回答by Anton
string.isdigit(g) returns False if g is negative or float. I prefer using following function:
如果 g 为负数或浮点数,则 string.isdigit(g) 返回 False。我更喜欢使用以下功能:
def is_digit(g):
try:
float(g)
except ValueError:
return False
return True
回答by msklc
maybe using .isalpha()is an easier way...
也许使用.isalpha()是一种更简单的方法......
so; instead of if not my_str.isdigit()you can try if my_str.isalpha()
所以; 而不是if not my_str.isdigit()你可以尝试if my_str.isalpha()
it is the shorter way to check if a string is not digit
这是检查字符串是否不是数字的更短方法

