如何在 python 中检查字符串是否只包含数字?

如何检查字符串是否只包含数字?

我已经试过了,我想看看最简单的方法。

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: ")
259518 次浏览

使用 str.isdigit:

>>> "12345".isdigit()
True
>>> "12345a".isdigit()
False
>>>

使用字符串 数字函数:

>>> s = '12345'
>>> s.isdigit()
True
>>> s = '1abc'
>>> s.isdigit()
False

您需要在 str对象上使用 isdigit方法:

if len(isbn) == 10 and isbn.isdigit():

来自 isdigit文档:

()

如果字符串中的所有字符都是数字且至少有一个字符,则返回 True,否则为 False。数字包括需要特殊处理的十进制字符和数字,如兼容性上标数字。这包括不能用来形成以10为基数的数字的数字,比如 Kharosthi 数字。在形式上,数字是具有属性值 Numeric _ Type = Digit 或 Numeric _ Type = Decimal 的字符。

你可以在这里使用 try catch block:

s="1234"
try:
num=int(s)
print "S contains only digits"
except:
print "S doesn't contain digits ONLY"

每次我在检查中遇到问题时,都是因为 str 有时可以是 Nothing,如果 str 可以是 Nothing,那么仅仅使用 str.isdigital ()是不够的,因为您会得到一个错误

AttributeError: ‘ NoneType’对象没有属性‘ isdigital’

然后您需要首先验证 str 是无还是无。为了避免多 if 分支,一个明确的方法是:

if str and str.isdigit():

希望这对像我这样有同样问题的人有所帮助。

关于 浮动数字底片数字等等,以前所有的例子都是错误的。

到目前为止,我得到了这样的东西,但我认为它可以更好:

'95.95'.replace('.','',1).isdigit()

只有在数字字符串中有一个或没有“。”时才返回 true。

'9.5.9.5'.replace('.','',1).isdigit()

将会返回虚假

也可以使用正则表达式,

import re

- 1) word = “3487954”

re.match('^[0-9]*$',word)

- 2) word = “3487.954”

re.match('^[0-9\.]*$',word)

- 3) word = “3487.954328”

re.match('^[0-9\.\ ]*$',word)

正如你可以看到所有3例意味着只有没有在你的字符串。因此,您可以遵循与它们一起给出的各自的解决方案。

正如在这个注释 如何在 python 中检查字符串是否只包含数字?中指出的那样,isdigit()方法对于这个用例并不完全准确,因为它对于一些类似数字的字符返回 True:

>>> "\u2070".isdigit() # unicode escaped 'superscript zero'
True

如果需要避免这种情况,下面的简单函数将检查字符串中的所有字符是否都是介于“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

用于问题中的例句:

if len(isbn) == 10 and contains_only_digits(isbn):
print ("Works")

我可以想到两种方法来检查一个字符串是否所有的数字都为 not

方法1(使用 python 中内置的 isdigital ()函数) :-

>>>st = '12345'
>>>st.isdigit()
True
>>>st = '1abcd'
>>>st.isdigit()
False

方法2(在字符串顶部执行异常处理) :-

st="1abcd"
try:
number=int(st)
print("String has all digits in it")
except:
print("String does not have all digits in it")

上述代码的输出结果如下:

String does not have all digits in it

可以使用 str.isdigital ()方法或 str.isnumeric ()方法

你也可以用这个:

re.match(r'^[\d]*$' , YourString)

解决方案:

def main():
isbn = input("Enter your 10 digit ISBN number: ")
try:
int(isbn)
is_digit = True
except ValueError:
is_digit = False
if len(isbn) == 10 and is_digit:
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: ")