Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the left part of a string?

Tags:

python

string

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

like image 774
grigoryvp Avatar asked Sep 26 '22 20:09

grigoryvp


People also ask

How do I remove part of a string?

You can also remove a specified character or substring from a string by calling the String. Replace(String, String) method and specifying an empty string (String. Empty) as the replacement. The following example removes all commas from a string.

How do you remove part of a string in Java?

The first and most commonly used method to remove/replace any substring is the replace() method of Java String class. The first parameter is the substring to be replaced, and the second parameter is the new substring to replace the first parameter.


1 Answers

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

like image 209
MrTopf Avatar answered Oct 19 '22 13:10

MrTopf