我剛開始使用python。下面是我的代碼,用于獲取字串中每個單詞的最后 3 個字符。有沒有辦法使用簡短的正則運算式語法來獲得相同的結果?
import re
names = 'steven thomas williams'
res = [x[0] for x in [[y.group() for y in re.finditer(r'.{3}$',z)] for z in names.split()]]
print(res) #['ven', 'mas', 'ams']
uj5u.com熱心網友回復:
字串切片
使用slicing它效率更高,而且您將只有一個 for 回圈,而不是 3
names = 'steven thomas williams'
res = [z[-3:] for z in names.split()]
print(res) # ['ven', 'mas', 'ams']
re.search
如果要使用re,請使用re.search
res = [re.search(r'.{3}$', z)[0] for z in names.split()]
安全
添加if len(z) >= 3到串列理解中以過濾太小的單詞
res = [z[-3:] for z in names.split() if len(z) >= 3]
res = [re.search(r'.{3}$', z)[0] for z in names.split() if len(z) >= 3]
uj5u.com熱心網友回復:
names='steven thomas williams'
names=names.split(" ")
for i in range(len(names)):
print(names[i][-3:])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/333179.html
