Skip to content
Advertisement

How to trim the characters in the string?

I have a list.

file_name = ['a.3903902.pdf','b.3432312.pdf','c.239002191.pdf','d.23423192010.pdf']

I want to trim the strings in the list to remove the characters including . sign and the numbers.

Expected output:

file_name = ['a.pdf','b.pdf','c.pdf','d.pdf']

Advertisement

Answer

You can use regex with pattern as r'.d+'. This will literally match . followed by one ore more digits.

>>> import re
>>> file_name = ['a.3903902.pdf','b.3432312.pdf','c.239002191.pdf','d.23423192010.pdf']
>>> [re.sub(r'.d+', '', f) for f in file_name]
['a.pdf', 'b.pdf', 'c.pdf', 'd.pdf']
Advertisement