How to remove the left part of a string?
- Question by grigoryvp
- Answer by Milovan Tomašević
Question by grigoryvp
I have some simple python code that searches files for a string e.g.
path=c:\path, where the
c:\path part may vary. The current code is:
def find_path(i_file): lines = open(i_file).readlines() for line in lines: if line.startswith("Path="): return # what to do here in order to get line content after "Path=" ?
What is a simple way to get the text after
Answer by Milovan Tomašević
removesuffix() string methods added in Python 3.9 due to issues associated with
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))
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)
['York', 'Zealand', 'Delhi', 'Now']