我有一个没有特定模式的字符串。我不得不寻找一些特定的词,然后提取一些信息。 目前我被困在查找字符串中最后一个数字的位置。Python找到字符串中最后一个数字的位置
因此,举例来说,如果:
mystring="The total income from company xy was 12320 for the last year and 11932 in the previous year"
我想找出最后一个数字的此字符串的位置。 所以结果在“70”位置应该是“2”。
我有一个没有特定模式的字符串。我不得不寻找一些特定的词,然后提取一些信息。 目前我被困在查找字符串中最后一个数字的位置。Python找到字符串中最后一个数字的位置
因此,举例来说,如果:
mystring="The total income from company xy was 12320 for the last year and 11932 in the previous year"
我想找出最后一个数字的此字符串的位置。 所以结果在“70”位置应该是“2”。
您可以用正则表达式做到这一点,这里的快速尝试:
>>>mo = re.match('.+([0-9])[^0-9]*$', mystring)
>>>print mo.group(1), mo.start(1)
2 69
这是一个基于0的位置当然是ition。
您可以通过枚举用生成器表达式循环从next
函数内尾随:
>>> next(i for i,j in list(enumerate(mystring,1))[::-1] if j.isdigit())
70
或者使用正则表达式:
>>> import re
>>>
>>> m=re.search(r'(\d)[^\d]*$',mystring)
>>> m.start()+1
70
def find_last(s):
temp = list(enumerate(s))
temp.reverse()
for pos, chr in temp:
try:
return(pos, int(chr))
except ValueError:
continue
虽然这可能会提供一个问题的答案,但它有助于提供一些评论,以便其他人可以了解此代码执行其功能的“原因”。请参阅[如何回答](http://stackoverflow.com/help/how-to-answer)了解更多细节/上下文到答案的方法。 –
将字符串中的所有数字保存在一个数组中,并弹出最后一个数字。
array = [int(s) for s in mystring.split() if s.isdigit()]
lastdigit = array.pop()
它比正则表达式更快,看起来比它更可读。
你可以扭转字符串,并用一个简单的正则表达式率先拿到赛:
s = mystring[::-1]
m = re.search('\d', s)
pos = len(s) - m.start(0)
获取答案不提供代码片段来检查。幸运! – Alfabravo