How to remove the left part of a string?

Solution 1:

If the string is fixed you can simply use:

if line.startswith("Path="):
    return line[5:]

which gives you everything from position 5 on in the string (a string is also a sequence so these sequence operators work here, too).

Or you can split the line at the first =:

if "=" in line:
    param, value = line.split("=",1)

Then param is "Path" and value is the rest after the first =.

Solution 2:

Remove prefix from a string

# ...
if line.startswith(prefix):
   return line[len(prefix):]

Split on the first occurrence of the separator via str.partition()

def findvar(filename, varname="Path", sep="=") :
    for line in open(filename):
        if line.startswith(varname + sep):
           head, sep_, tail = line.partition(sep) # instead of `str.split()`
           assert head == varname
           assert sep_ == sep
           return tail

Parse INI-like file with ConfigParser

from ConfigParser import SafeConfigParser
config = SafeConfigParser()
config.read(filename) # requires section headers to be present

path = config.get(section, 'path', raw=1) # case-insensitive, no interpolation

Other options

  • str.split()
  • re.match()

Solution 3:

Starting in Python 3.9, you can use removeprefix:

'Path=helloworld'.removeprefix('Path=')
# 'helloworld'

Solution 4:

Any Python version:

def remove_prefix(text, prefix):
    return text[len(prefix):] if text.startswith(prefix) else text

Python 3.9+

text.removeprefix(prefix)