[英]Python find position of last digit in string
我有一串沒有特定圖案的字符。 我必須尋找一些特定的單詞,然后提取一些信息。 目前,我一直在尋找字符串中最后一個數字的位置。
因此,例如:
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開始的位置。
您可以使用生成器表達式遍歷枚舉,而后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
將字符串中的所有數字保存在數組中,然后從中彈出最后一個數字。
array = [int(s) for s in mystring.split() if s.isdigit()]
lastdigit = array.pop()
它比正則表達式更快,並且比它更易讀。
def find_last(s):
temp = list(enumerate(s))
temp.reverse()
for pos, chr in temp:
try:
return(pos, int(chr))
except ValueError:
continue
您可以反轉字符串並使用簡單的正則表達式獲得第一個匹配項:
s = mystring[::-1]
m = re.search('\d', s)
pos = len(s) - m.start(0)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.