파이썬으로 문자열이 숫자로 시작하는지 확인하는 방법은 무엇입니까?
숫자(0-9부터)로 시작하는 문자열이 있습니다. starts with()를 사용하여 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
더 현명하고 효율적인 방법이 있습니까?
파이썬의string
도서관은 가지고 있습니다.isdigit()
방법:
string[0].isdigit()
>>> string = '1abc'
>>> string[0].isdigit()
True
그렇게 오랜 시간이 지난 후에도 여전히 최고의 답이 없다는 것이 놀랍습니다.
다른 답변의 단점은 다음과 같습니다.[0]
첫 번째 문자를 선택할 수 있지만, 언급한 대로 빈 문자열에서 이 문자가 끊어집니다.
다음을 사용하면 이 문제를 피할 수 있으며, 제 생각에 우리가 가지고 있는 옵션 중 가장 예쁘고 읽기 쉬운 구문을 제공할 수 있습니다.또한 정규식을 가져오거나 방해하지 않습니다.):
>>> string = '1abc'
>>> string[:1].isdigit()
True
>>> string = ''
>>> string[:1].isdigit()
False
때때로, 당신은 정규식을 사용할 수 있습니다.
>>> import re
>>> re.search('^\s*[0-9]',"0abc")
<_sre.SRE_Match object at 0xb7722fa8>
코드가 작동하지 않습니다. 필요합니다.or
대신에||
.
해라
'0' <= strg[:1] <= '9'
또는
strg[:1] in '0123456789'
아니면, 만약 당신이 정말로 미친다면.startswith
,
strg.startswith(('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'))
다음 코드:
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
내장 문자열 모듈 사용:
>>> import string
>>> '30 or older'.startswith(tuple(string.digits))
허용된 답변은 단일 문자열에 적합합니다.저는 판다와 함께 일할 수 있는 방법이 필요했습니다.Series.str.contains.잘 알려지지 않은 것처럼 보이는 정규식과 모듈의 유용한 사용을 사용하는 것보다 거의 틀림없이 더 읽을 수 있습니다.
여기 저의 "답변"이 있습니다(여기서 독특해지려고 노력하는, 저는 실제로 이 특정한 경우에도 추천하지 않습니다:-).
//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
(참) 및1 < 3 < 2
(거짓) 및(1 < 3) < 2
(참).이것은 대부분의 다른 언어에서는 작동하지 않습니다.)
정규식 사용:
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] 파는 모든 숫자와 일치하며 문자열 [:1]은 문자열의 첫 번째 문자와 일치합니다.
메서드의 기능을 확장하려면 정규식을 사용합니다.
사용해 보십시오.
if string[0] in range(10):
언급URL : https://stackoverflow.com/questions/5577501/how-to-tell-if-string-starts-with-a-number-with-python
'programing' 카테고리의 다른 글
ORACLE에서 CTE 및 테이블 업데이트 (0) | 2023.08.10 |
---|---|
MutableLiveData에서 setValue()와 postValue()의 차이 (0) | 2023.08.10 |
C의 char to int 변환 (0) | 2023.08.10 |
프래그먼트로 데이터 바인딩을 사용하는 방법 (0) | 2023.08.10 |
Raspberry Pi4, mariadb 설치, mysql command에서 문제를 찾을 수 없습니다. (0) | 2023.08.10 |