Swe*_*abh 0 python regex string numbers
我有类似6M1D14M的字符串。我想从该字符串中提取所有数字。就像是:
[6, 1, 14]
Run Code Online (Sandbox Code Playgroud)
我怎么做?字符串的长度可以是任意的。介于两者之间的数字也可以是任意长度。
我已经尝试过这种方法,但是无法按照需要的方式拆分字符串。
findAll与正则表达式一起使用\d+
>>> import re
>>> re.findall(r"\d+", "6M1D14M")
['6', '1', '14']
Run Code Online (Sandbox Code Playgroud)
对于转换为整数列表,只需对其进行迭代和解析。
>>> import re
>>> [int(num) for num in re.findall(r"\d+", "6M1D14M")]
[6, 1, 14]
Run Code Online (Sandbox Code Playgroud)