[英]Extract digits from string by condition
I want to extract digits from a short string, base on a condition that the digits is in front of a character ( S
flag).我想从短字符串中提取数字,条件是数字位于字符(
S
标志)前面。
example and result:示例和结果:
> string = '10M26S'
> 26
> string = '18S8M10S'
> [18,10] OR 28
> string = '7S29M'
> 7
I can split the string to a list to get the individual element,我可以将字符串拆分为列表以获取单个元素,
result = [''.join(g) for _, g in groupby('18S8M10S', str.isalpha)]
> ['18', 'S', '8', 'M', '10', 'S']
but how could I just get the 18
and 10
?但我怎么能得到
18
和10
呢?
Use re.findall
with the regex r'(\\d+)S'
.将
re.findall
与正则表达式r'(\\d+)S'
。 This matches all digits before a capital S
.这匹配大写
S
之前的所有数字。
>>> string = '10M26S'
>>> re.findall(r'(\d+)S',string)
['26']
>>> string = '18S8M10S'
>>> re.findall(r'(\d+)S',string)
['18', '10']
>>> string = '7S29M'
>>> re.findall(r'(\d+)S',string)
['7']
To get integer output, you can convert them in a list comp or use map
要获得整数输出,您可以将它们转换为列表格式或使用
map
>>> list(map(int,['18', '10']))
[18, 10]
You could use a regular expression .您可以使用正则表达式。
import re
regex = r"(\d+)S"
match = re.search(regex, '10M26S')
print(match.group(1)) # '26'
import re
[int(m) for m in re.findall(r'(\d+)S', "input10string30")]
this should do the trick这应该可以解决问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.