How to remove the left part of a string?


I have some simple python code that searches files for a string e.g. path=c:\path, whereby the c:\path may vary. The current code is:

def findPath( 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 a string text after Path=? Is there a simple method, without closures, reflection or other esoteric things ?

9/1/2016 1:38:36 PM

Accepted Answer

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 =.

7/15/2011 7:54:59 PM

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() # requires section headers to be present

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

Other options

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow