你如何在python中检查一个字符串是否只包含数字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21388541/
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
How do you check in python whether a string contains only numbers?
提问by Coder77
How do you check whether a string contains only numbers?
你如何检查一个字符串是否只包含数字?
I've given it a go here. I'd like to see the simplest way to accomplish this.
我已经试过了。我想看看实现这一目标的最简单方法。
import string
def main():
isbn = input("Enter your 10 digit ISBN number: ")
if len(isbn) == 10 and string.digits == True:
print ("Works")
else:
print("Error, 10 digit number was not inputted and/or letters were inputted.")
main()
if __name__ == "__main__":
main()
input("Press enter to exit: ")
采纳答案by mhlester
You'll want to use the isdigitmethod on your strobject:
您需要isdigit在str对象上使用该方法:
if len(isbn) == 10 and isbn.isdigit():
From the isdigitdocumentation:
str.isdigit()Return true if all characters in the string are digits and there is at least one character, false otherwise.
For 8-bit strings, this method is locale-dependent.
str.isdigit()如果字符串中的所有字符都是数字并且至少有一个字符,则返回 true,否则返回 false。
对于 8 位字符串,此方法取决于语言环境。
回答by Coder77
回答by ndpu
回答by cold_coder
You can use try catch block here:
您可以在此处使用 try catch 块:
s="1234"
try:
num=int(s)
print "S contains only digits"
except:
print "S doesn't contain digits ONLY"
回答by zhihong
As every time I encounter an issue with the check is because the str can be None sometimes, and if the str can be None, only use str.isdigit() is not enough as you will get an error
每次我遇到检查问题时都是因为 str 有时可以是 None ,如果 str 可以是 None,只使用 str.isdigit() 是不够的,因为你会得到一个错误
AttributeError: 'NoneType' object has no attribute 'isdigit'
AttributeError: 'NoneType' 对象没有属性 'isdigit'
and then you need to first validate the str is None or not. To avoid a multi-if branch, a clear way to do this is:
然后您需要首先验证 str 是否为 None 。为了避免多 if 分支,一个明确的方法是:
if str and str.isdigit():
Hope this helps for people have the same issue like me.
希望这对像我一样有同样问题的人有所帮助。
回答by Joe9008
What about of float numbers, negativesnumbers, etc.. All the examples before will be wrong.
关于什么浮点数,底片号码等。所有的例子之前,将是错误的。
Until now I got something like this, but I think it could be a lot better:
到目前为止,我得到了这样的东西,但我认为它可能会好得多:
'95.95'.replace('.','',1).isdigit()
will return true only if there is one or no '.' in the string of digits.
仅当有一个或没有 '.' 时才返回 true。在数字串中。
'9.5.9.5'.replace('.','',1).isdigit()
will return false
会返回假
回答by Devendra Bhat
You can also use the regex,
您还可以使用正则表达式,
import re
eg:-1) word = "3487954"
例如:-1) word = "3487954"
re.match('^[0-9]*$',word)
eg:-2) word = "3487.954"
例如:-2) word = "3487.954"
re.match('^[0-9\.]*$',word)
eg:-3) word = "3487.954 328"
例如:-3) word = "3487.954 328"
re.match('^[0-9\.\ ]*$',word)
As you can see all 3 eg means that there is only no in your string. So you can follow the respective solutions given with them.
如您所见,所有 3 个 eg 表示您的字符串中只有 no。所以你可以按照他们给出的相应解决方案进行操作。
回答by mit
As pointed out in this comment How do you check in python whether a string contains only numbers?the isdigit()method is not totally accurate for this use case, because it returns True for some digit-like characters:
正如此评论中所指出的,您如何在 python 中检查字符串是否仅包含数字?该isdigit()方法对于这个用例并不完全准确,因为它对于一些类似数字的字符返回 True:
>>> "\u2070".isdigit() # unicode escaped 'superscript zero'
True
If this needs to be avoided, the following simple function checks, if all characters in a string are a digit between "0" and "9":
如果需要避免这种情况,下面的简单函数会检查字符串中的所有字符是否都是“0”和“9”之间的数字:
import string
def contains_only_digits(s):
# True for "", "0", "123"
# False for "1.2", "1,2", "-1", "a", "a1"
for ch in s:
if not ch in string.digits:
return False
return True
Used in the example from the question:
在问题的示例中使用:
if len(isbn) == 10 and contains_only_digits(isbn):
print ("Works")
回答by Rahul
There are 2 methods that I can think of to check whether a string has all digits of not
我可以想到两种方法来检查字符串是否包含所有数字不
Method 1(Using the built-in isdigit() function in python):-
方法一(使用python内置的isdigit()函数):-
>>>st = '12345'
>>>st.isdigit()
True
>>>st = '1abcd'
>>>st.isdigit()
False
Method 2(Performing Exception Handling on top of the string):-
方法 2(在字符串顶部执行异常处理):-
st="1abcd"
try:
number=int(st)
print("String has all digits in it")
except:
print("String does not have all digits in it")
The output of the above code will be:
上述代码的输出将是:
String does not have all digits in it
回答by Faith
you can use str.isdigit() method or str.isnumeric() method
您可以使用 str.isdigit() 方法或 str.isnumeric() 方法

