Programing

문자열에 숫자 만 포함되어 있는지 파이썬에서 어떻게 확인합니까?

crosscheck 2020. 8. 16. 19:14
반응형

문자열에 숫자 만 포함되어 있는지 파이썬에서 어떻게 확인합니까?


문자열에 숫자 만 포함되어 있는지 어떻게 확인합니까?

나는 그것을 여기에 주었다. 이 작업을 수행하는 가장 간단한 방법을보고 싶습니다.

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

객체에 isdigit메서드 를 사용하고 싶을 것입니다 str.

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

로부터 isdigit문서 :

str.isdigit()

문자열의 모든 문자가 숫자이고 하나 이상의 문자가 있으면 true를 반환하고 그렇지 않으면 false를 반환합니다.

8 비트 문자열의 경우이 방법은 로케일에 따라 다릅니다.


사용 str.isdigit:

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

문자열 isdigit 함수 사용 :

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

여기에서 try catch 블록을 사용할 수 있습니다.

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

수표에 문제가 발생할 때마다 str이 때때로 None 일 수 있기 때문에 str이 None 일 수 있다면 str.isdigit () 만 사용하면 오류가 발생하므로 충분하지 않습니다.

AttributeError : 'NoneType'개체에 'isdigit'속성이 없습니다.

그런 다음 먼저 str이 None인지 아닌지 확인해야합니다. multi-if 분기를 피하려면 다음과 같은 명확한 방법이 있습니다.

if str and str.isdigit():

이것이 사람들이 나와 같은 문제를 갖는 데 도움이되기를 바랍니다.


부동 숫자 , 음수은 어떻습니까? 이전의 모든 예제는 잘못 될 것입니다.

지금까지 이와 같은 것을 얻었지만 훨씬 더 나을 수 있다고 생각합니다.

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

'.'가 하나 없거나없는 경우에만 true를 반환합니다. 숫자 열에서.

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

거짓을 반환합니다


이 주석에서 지적했듯이 문자열에 숫자 만 포함되어 있는지 파이썬에서 어떻게 확인합니까? 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":

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

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.


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

참고URL : https://stackoverflow.com/questions/21388541/how-do-you-check-in-python-whether-a-string-contains-only-numbers

반응형