Home > Software engineering >  How to get the last 3 characters of each word of a given string using short regex syntax?
How to get the last 3 characters of each word of a given string using short regex syntax?

Time:10-24

I'm just starting with python. Below is my code to get the last 3 characters of each word in string. Is there a way to use a short regex syntax to get the same result?

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']

CodePudding user response:

String slicing

Use slicing that is so much more efficient, and also you'll have only one for loop, instead of 3

names = 'steven thomas williams'
res = [z[-3:] for z in names.split()]
print(res)  # ['ven', 'mas', 'ams']

re.search

If you want to use re, use re.search

res = [re.search(r'.{3}$', z)[0] for z in names.split()]

Safety

Add if len(z) >= 3 into the list comprenhension to filter too small words

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]

CodePudding user response:

names='steven thomas williams'
names=names.split(" ")
for i in range(len(names)):
    print(names[i][-3:])
  • Related