繁体   English   中英

如何使用简短的正则表达式语法获取给定字符串的每个单词的最后 3 个字符?

[英]How to get the last 3 characters of each word of a given string using short regex syntax?

我刚开始使用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']

字符串切片

使用效率更高的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]
names='steven thomas williams' names=names.split(" ") for i in range(len(names)): print(names[i][-3:])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM