次のような文字列があるとします
"There are LJFK$(#@$34)(,0,ksdjf apples in the (4,5)"
数値をリストに動的に抽出できるようにしたい: [34, 0, 4, 5]
.
Pythonでこれを行う簡単な方法はありますか?
言い換えれば、
区切り文字で区切られた連続した数値クラスターを抽出する方法はありますか?
もちろん、正規表現を使用してください:
>>> s = "There are LJFK$(#@$34)(,0,ksdjf apples in the (4,5)"
>>> import re
>>> list(map(int, re.findall(r'[0-9]+', s)))
[34, 0, 4, 5]
正規表現なしでこれを行うこともできますが、もう少し作業が必要です。
>>> s = "There are LJFK$(#@$34)(,0,ksdjf apples in the (4,5)"
>>> #replace nondigit characters with a space
... s = "".join(x if x.isdigit() else " " for x in s)
>>> print s
34 0 4 5
>>> #get the separate digit strings
... digitStrings = s.split()
>>> print digitStrings
['34', '0', '4', '5']
>>> #convert strings to numbers
... numbers = map(int, digitStrings)
>>> print numbers
[34, 0, 4, 5]