14 回复 | 直到 1 年前
1
430
3 年前
如果只想提取正整数,请尝试以下操作:
>>> str = "h3110 23 cat 444.4 rabbit 11 2 dog"
>>> [int(s) for s in str.split() if s.isdigit()]
[23, 11, 2]
我认为这比regex示例好有三个原因。首先,您不需要另一个模块;其次,它更可读,因为您不需要解析regex mini语言;第三,它更快(因此可能更像是pythonic):
python -m timeit -s "str = 'h3110 23 cat 444.4 rabbit 11 2 dog' * 1000" "[s for s in str.split() if s.isdigit()]"
100 loops, best of 3: 2.84 msec per loop
python -m timeit -s "import re" "str = 'h3110 23 cat 444.4 rabbit 11 2 dog' * 1000" "re.findall('\\b\\d+\\b', str)"
100 loops, best of 3: 5.66 msec per loop
这将无法识别浮点数、负整数或十六进制格式的整数。如果你不能接受这些限制,
slim's answer below
会成功的。
2
404
4 年前
我会用regexp:
>>> import re
>>> re.findall(r'\d+', 'hello 42 I\'m a 32 string 30')
['42', '32', '30']
这也将匹配来自
bla42bla
. 如果只希望数字由单词边界(空格、句点、逗号)分隔,则可以使用\b:
>>> re.findall(r'\b\d+\b', 'he33llo 42 I\'m a 32 string 30')
['42', '32', '30']
以数字列表而不是字符串列表结束:
>>> [int(s) for s in re.findall(r'\b\d+\b', 'he33llo 42 I\'m a 32 string 30')]
[42, 32, 30]
3
81
2 年前
这已经有点晚了,但是您也可以扩展regex表达式来解释科学符号。
import re
# Format is [(, ), ...]
ss = [("apple-12.34 ba33na fanc-14.23e-2yapple+45e5+67.56E+3",
['-12.34',