![](/img/trans.png)
[英]How I can get last word in the given string without using if condition for index?
[英]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.