python - 获取由未知分隔符分隔的字符串中的最后一个数字
问题描述
我正在尝试解析标题,但我无法弄清楚如何隔离字符串中的最后一个数字,我想我已经弄清楚了分隔符(使用那些嵌套的 if 语句),但我仍然没有通过我自己的测试用例。有什么建议吗?
电流输出:
1801 (150@$5): 1801
0055 30 @ $5: 0055
leaver - 8 @ $10: 8
ATS-55) - 45/$2: 55
最终目标:
1801 (150@$5): 150
0055 30 @ $5: 30
leaver - 8 @ $10: 8
ATS-55) - 45/$2: 45
我的代码
import re
def getSlots(title):
x=title.split('@')
if len(x)<2: #this means @ wasnt used as the delimeter
x=title.split('/')
if len(x)<2:
x=title.split(' ')
if len(x)<2:
return "unsolvable";
m = re.search('\d+', x[0])
return m.group(0);
testlist=['1801 (150@$5)','0055 30 @ $5','leaver - 8 @ $10','ATS-55) - 45/$2']
for t in testlist:
print(t+': '+getSlots(t))
解决方案
假设您要查找的数字始终是美元符号左侧的一组连续、连续的数字,则类似以下内容似乎有效:
lines = [
'1801 (150@$5): 1801',
'0055 30 @ $5: 0055',
'leaver - 8 @ $10: 8',
'ATS-55) - 45/$2: 55',
]
def extract(line):
# Assumes there's only one $ symbol
dsp = line.index('$')
# Find last index
last_index = dsp - 1
while not line[last_index].isdigit():
last_index -= 1
# Find first index
first_index = last_index
while line[first_index-1].isdigit():
first_index -= 1
return line[first_index:last_index+1]
for line in lines:
print(extract(line))
结果:
'1801 (150@$5): 1801' => 150 '0055 30 @ $5: 0055' => 30 '离开者 - 8 @ $10: 8' => 8 'ATS-55) - 45/$2: 55',150 => 45
注意返回值extract()
是一个字符串,你可能希望把它转换成一个int。