반응형
질문
문자열에 포함된 모든 숫자를 추출하고 싶습니다. 이를 위해 정규 표현식이나 isdigit()
메소드 중 어떤 것이 더 적합한가요?
예시:
line = "hello 12 hi 89"
결과:
[12, 89]
답변
I'd use a regexp :
>>> import re
>>> re.findall(r'\d+', "hello 42 I'm a 32 string 30")
['42', '32', '30']
This would also match 42 from bla42bla
. If you only want numbers delimited by word boundaries (space, period, comma), you can use \b :
>>> re.findall(r'\b\d+\b', "he33llo 42 I'm a 32 string 30")
['42', '32', '30']
To end up with a list of numbers instead of a list of strings:
>>> [int(s) for s in re.findall(r'\b\d+\b', "he33llo 42 I'm a 32 string 30")]
[42, 32, 30]
NOTE: this does not work for negative integers
반응형
댓글