简体   繁体   English

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

[英]How do you check in python whether a string contains only numbers?

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

You'll want to use the isdigit method on your str object:您需要在str对象上使用isdigit方法:

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

From the isdigit documentation :isdigit文档

str.isdigit() str.isdigit()

Return True if all characters in the string are digits and there is at least one character, False otherwise.如果字符串中的所有字符都是数字并且至少有一个字符,则返回 True,否则返回 False。 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.这涵盖了不能用于​​以 10 为基数形成数字的数字,例如 Kharosthi 数字。 Formally, a digit is a character that has the property value Numeric_Type=Digit or Numeric_Type=Decimal.形式上,数字是具有属性值 Numeric_Type=Digit 或 Numeric_Type=Decimal 的字符。

Use str.isdigit :使用str.isdigit

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

Use string isdigit function:使用字符串isdigit函数:

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

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.如您所见,所有 3 eg 意味着您的字符串中只有 no 。 So you can follow the respective solutions given with them.因此,您可以按照他们提供的相应解决方案进行操作。

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 '.'仅当有一个或没有 '.' 时才会返回 true。 in the string of digits.在数字串中。

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

will return false将返回 false

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.然后您需要首先验证 str 是否为 None 。 To avoid a multi-if branch, a clear way to do this is:为了避免多重 if 分支,一个明确的方法是:

if str and str.isdigit():

Hope this helps for people have the same issue like me.希望这对像我一样有同样问题的人有所帮助。

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"

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):-方法1(使用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

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

你也可以使用这个:

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

Solution:解决方案:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM