removeprefix()
and removesuffix()
string methods added in Python 3.9 due to issues associated with lstrip
and rstrip
interpretation of parameters passed to them. Read PEP 616 for more details.
# in python 3.9
>>> s = 'python_390a6'
# apply removeprefix()
>>> s.removeprefix('python_')
'390a6'
# apply removesuffix()
>>> s = 'python.exe'
>>> s.removesuffix('.exe')
'python'
# in python 3.8 or before
>>> s = 'python_390a6'
>>> s.lstrip('python_')
'390a6'
>>> s = 'python.exe'
>>> s.rstrip('.exe')
'python'
removesuffix
example with a list:
plurals = ['cars', 'phones', 'stars', 'books']
suffix = 's'
for plural in plurals:
print(plural.removesuffix(suffix))
output:
car
phone
star
book
removeprefix
example with a list:
places = ['New York', 'New Zealand', 'New Delhi', 'New Now']
shortened = [place.removeprefix('New ') for place in places]
print(shortened)
output:
['York', 'Zealand', 'Delhi', 'Now']