IT박스

파이썬에서 문자열이 숫자로 시작하는지 확인하는 방법은 무엇입니까?

itboxs 2020. 11. 7. 09:06
반응형

파이썬에서 문자열이 숫자로 시작하는지 확인하는 방법은 무엇입니까?


숫자 (0-9)로 시작하는 문자열이 있습니다. startswith ()를 사용하여 "또는"10 개의 테스트 케이스를 사용할 수 있지만 더 깔끔한 솔루션이있을 수 있습니다.

그래서 글을 쓰는 대신

if (string.startswith('0') || string.startswith('2') ||
    string.startswith('3') || string.startswith('4') ||
    string.startswith('5') || string.startswith('6') ||
    string.startswith('7') || string.startswith('8') ||
    string.startswith('9')):
    #do something

더 영리하고 효율적인 방법이 있습니까?


Python의 string라이브러리에는 다음과 같은 isdigit()방법이 있습니다.

string[0].isdigit()


>>> string = '1abc'
>>> string[0].isdigit()
True

코드가 작동하지 않습니다. 당신이 필요로 or하는 대신 ||.

시험

'0' <= strg[:1] <= '9'

또는

strg[:1] in '0123456789'

또는에 대해 정말로 열광한다면 startswith,

strg.startswith(('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'))

때로는 정규식을 사용할 수 있습니다.

>>> import re
>>> re.search('^\s*[0-9]',"0abc")
<_sre.SRE_Match object at 0xb7722fa8>

for s in ("fukushima", "123 is a number", ""):

    print s.ljust(20),  s[0].isdigit() if s else False

결과

fukushima            False
123 is a number      True
                     False

다음을 사용할 수도 있습니다 try...except.

try:
    int(string[0])
    # do your stuff
except:
    pass # or do your stuff

여기에 내 "답변"이 있습니다 (여기에서 고유하도록 노력하고 있지만 실제로이 특정 경우에 대해 권장하지 않습니다. :-)

사용 ord ()특별한 a <= b <= c형태 :

//starts_with_digit = ord('0') <= ord(mystring[0]) <= ord('9')
//I was thinking too much in C. Strings are perfectly comparable.
starts_with_digit = '0' <= mystring[0] <= '9'

(이와 a <= b <= c같이 a < b < c는 특별한 파이썬 구조이며, 비교 1 < 2 < 3(true), 1 < 3 < 2(false), (1 < 3) < 2(true) 와 같이 깔끔 합니다. 이것은 대부분의 다른 언어에서 작동하는 방식이 아닙니다.)

정규식 사용 :

import re
//starts_with_digit = re.match(r"^\d", mystring) is not None
//re.match is already anchored
starts_with_digit = re.match(r"\d", mystring) is not None

정규식을 사용할 수 있습니다 .

다음을 사용하여 숫자를 감지 할 수 있습니다.

if(re.search([0-9], yourstring[:1])):
#do something

[0-9] 파는 모든 숫자와 일치하고 yourstring [: 1]은 문자열의 첫 번째 문자와 일치합니다.


놀랍게도 오랜 시간이 지난 후에도 여전히 최선의 답변이 누락되어 있습니다.

다른 답변의 단점은 [0]첫 번째 문자를 선택하는 데 사용 되지만 언급했듯이 빈 문자열에서 끊어집니다.

Using the following circumvents this problem, and, in my opinion, gives the prettiest and most readable syntax of the options we have. It also does not import/bother with regex either):

>>> string = '1abc'
>>> string[:1].isdigit()
True

>>> string = ''
>>> string[:1].isdigit()
False

Use Regular Expressions, if you are going to somehow extend method's functionality.


Try this:

if string[0] in range(10):

참고URL : https://stackoverflow.com/questions/5577501/how-to-tell-if-string-starts-with-a-number-with-python

반응형