How to remove the left part of a string?

How to remove the left part of a string?

  1. Question by grigoryvp
  2. 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 Path=?

Answer by Milovan Tomašević

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_')

# apply removesuffix()
>>> s = 'python.exe'
>>> s.removesuffix('.exe')

# in python 3.8 or before
>>> s = 'python_390a6'
>>> s.lstrip('python_')

>>> s = 'python.exe'
>>> s.rstrip('.exe')

removesuffix example with a list:

plurals = ['cars', 'phones', 'stars', 'books']
suffix = 's'

for plural in plurals:



removeprefix example with a list:

places = ['New York', 'New Zealand', 'New Delhi', 'New Now']

shortened = [place.removeprefix('New ') for place in places]


['York', 'Zealand', 'Delhi', 'Now']

Improve this page: 

Share on:      

Comments 💬