问题:您如何在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: ")

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: ")

回答 0

您需要isdigitstr对象上使用方法:

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

isdigit文档中

str.isdigit()

如果字符串中的所有字符都是数字并且至少有一个字符,则返回True,否则返回False。数字包括需要特殊处理的十进制字符和数字,例如兼容性上标数字。它涵盖了不能用于​​以10为底的数字的数字,例如Kharosthi数字。形式上,数字是具有属性值Numeric_Type =数字或Numeric_Type =十进制的字符。

You’ll want to use the isdigit method on your str object:

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

From the isdigit documentation:

str.isdigit()

Return True if all characters in the string are digits and there is at least one character, False otherwise. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the Kharosthi numbers. Formally, a digit is a character that has the property value Numeric_Type=Digit or Numeric_Type=Decimal.


回答 1

用途str.isdigit

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

Use str.isdigit:

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

回答 2

使用字符串isdigit函数:

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

Use string isdigit function:

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

回答 3

您还可以使用正则表达式,

import re

例如:-1)word =“ 3487954”

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

例如:-2)word =“ 3487.954”

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

例如:-3)word =“ 3487.954 328”

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

如您所见,所有3个eg表示您的字符串中没有任何内容。因此,您可以按照其提供的相应解决方案进行操作。

You can also use the regex,

import re

eg:-1) word = “3487954”

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

eg:-2) word = “3487.954”

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

eg:-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.


回答 4

关于什么浮点数底片号码等。所有的例子之前,将是错误的。

到现在为止,我得到了类似的东西,但我认为它可能会好得多:

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

仅当存在一个或没有“。”时返回true。在数字字符串中。

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

将返回假

What about of float numbers, negatives numbers, 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.

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

will return false


回答 5

正如该评论所指出的,如何检查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")

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:

>>> "\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”:

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

回答 6

您可以在此处使用try catch块:

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

You can use try catch block here:

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

回答 7

因为每次我遇到检查问题都是因为str有时可以为None,并且如果str可以为None,则仅使用str.isdigit()是不够的,因为您会得到一个错误

AttributeError:’NoneType’对象没有属性’isdigit’

然后您需要首先验证str是否为None。为了避免多if分支,一种清晰的方法是:

if str and str.isdigit():

希望这对像我这样的人有帮助。

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

AttributeError: ‘NoneType’ object has no attribute ‘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:

if str and str.isdigit():

Hope this helps for people have the same issue like me.


回答 8

我可以想到2种方法来检查字符串是否具有全位数

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

>>>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

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):-

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

Method 2(Performing Exception Handling on top of the string):-

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

回答 9

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

you can use str.isdigit() method or str.isnumeric() method


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。