How to remove the left part of a string?

PythonString

Python Problem Overview


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

Python Solutions


Solution 1 - Python

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 - Python

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

Solution 3 - Python

Starting in Python 3.9, you can use removeprefix:

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

Solution 4 - Python

Python 3.9+

text.removeprefix(prefix)

Any Python version:

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

Solution 5 - Python

For slicing (conditional or non-conditional) in general I prefer what a colleague suggested recently; Use replacement with an empty string. Easier to read the code, less code (sometimes) and less risk of specifying the wrong number of characters. Ok; I do not use Python, but in other languages I do prefer this approach:

rightmost = full_path.replace('Path=', '', 1)

or - to follow up to the first comment to this post - if this should only be done if the line starts with Path:

rightmost = re.compile('^Path=').sub('', full_path)

The main difference to some of what has been suggested above is that there is no "magic number" (5) involved, nor any need to specify both '5' and the string 'Path=', In other words I prefer this approach from a code maintenance point of view.

Solution 6 - Python

I prefer pop to indexing [-1]:

value = line.split("Path=", 1).pop()

to

value = line.split("Path=", 1)[1]
param, value = line.split("Path=", 1)

Solution 7 - Python

Or why not

if line.startswith(prefix):
    return line.replace(prefix, '', 1)

Solution 8 - Python

The simplest way I can think of is with slicing:

def find_path(i_file): 
    lines = open(i_file).readlines() 
    for line in lines: 
        if line.startswith("Path=") : 
            return line[5:]

A quick note on slice notation, it uses two indices instead of the usual one. The first index indicates the first element of the sequence you want to include in the slice and the last index is the index immediately after the last element you wish to include in the slice.
Eg:

sequence_obj[first_index:last_index]

The slice consists of all the elements between first_index and last_index, including first_index and not last_index. If the first index is omitted, it defaults to the start of the sequence. If the last index is omitted, it includes all elements up to the last element in the sequence. Negative indices are also allowed. Use Google to learn more about the topic.

Solution 9 - Python

import re

p = re.compile(r'path=(.*)', re.IGNORECASE)

path = "path=c:\path"

re.match(p, path).group(1)

Output:

'c:\\path'

Solution 10 - Python

How about..

line = r'path=c:\path'
line.partition('path=')

Output:

('', 'path=', 'c:\\path')

This triplet is the head, separator, and tail.

Solution 11 - Python

Another simple one-liner that hasn't been mentioned here:

value = line.split("Path=", 1)[-1]

This will also work properly for various edge cases:

>>> print("prefixfoobar".split("foo", 1)[-1])
"bar"

>>> print("foofoobar".split("foo", 1)[-1])
"foobar"

>>> print("foobar".split("foo", 1)[-1])
"bar"

>>> print("bar".split("foo", 1)[-1])
"bar"

>>> print("".split("foo", 1)[-1])
""

Solution 12 - Python

line[5:]

gives you characters after the first five.

Solution 13 - Python

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

output:

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)

output:

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

Solution 14 - Python

line[5:] will give the substring you want. Search the introduction and look for 'slice notation'

Solution 15 - Python

If you know list comprehensions:

lines = [line[5:] for line in file.readlines() if line[:5] == "Path="]

Solution 16 - Python

Why not using regex with escape? ^ matches the initial part of a line and re.MULTILINE matches on each line. re.escape ensures that the matching is exact.

>>> print(re.sub('^' + re.escape('path='), repl='', string='path=c:\path\nd:\path2', flags=re.MULTILINE))
c:\path
d:\path2

Solution 17 - Python

Try Following code

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

Solution 18 - Python

I guess this what you are exactly looking for

    def findPath(i_file) :
        lines = open( i_file ).readlines()
        for line in lines :
	        if line.startswith( "Path=" ):
		        output_line=line[(line.find("Path=")+len("Path=")):]
		        return output_line

Solution 19 - Python

The pop version wasn't quite right. I think you want:

>>> print('foofoobar'.split('foo', 1).pop())
foobar

Solution 20 - Python

The below method can be tried.

def remove_suffix(string1, suffix):
    length = len(suffix)

    if string1[0:length] == suffix:
        return string1[length:]
    else:
        return string1

suffix = "hello"
string1 = "hello world"

final_string = remove_suffix(string1, suffix)
print (final_string)

Solution 21 - Python

without having a to write a function, this will split according to list, in this case 'Mr.|Dr.|Mrs.', select everything after split with [1], then split again and grab whatever element. In the case below, 'Morris' is returned.

re.split('Mr.|Dr.|Mrs.', 'Mr. Morgan Morris')[1].split()[1]

Solution 22 - Python

This is very similar in technique to other answers, but with no repeated string operations, ability to tell if the prefix was there or not, and still quite readable:

parts = the_string.split(prefix_to_remove, 1):
    if len(parts) == 2:
        #  do things with parts[1]
        pass

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiongrigoryvpView Question on Stackoverflow
Solution 1 - PythonMrTopfView Answer on Stackoverflow
Solution 2 - PythonjfsView Answer on Stackoverflow
Solution 3 - PythonXavier GuihotView Answer on Stackoverflow
Solution 4 - PythonDavid FosterView Answer on Stackoverflow
Solution 5 - PythonfredarinView Answer on Stackoverflow
Solution 6 - PythonThomas SchreiberView Answer on Stackoverflow
Solution 7 - PythonJohn DamenView Answer on Stackoverflow
Solution 8 - PythonbatbratView Answer on Stackoverflow
Solution 9 - PythonrizaView Answer on Stackoverflow
Solution 10 - PythonFloggedhorseView Answer on Stackoverflow
Solution 11 - PythonpR0PsView Answer on Stackoverflow
Solution 12 - PythonSteven HuwigView Answer on Stackoverflow
Solution 13 - PythonMilovan TomaševićView Answer on Stackoverflow
Solution 14 - PythonPete KirkhamView Answer on Stackoverflow
Solution 15 - PythonMatthew SchinckelView Answer on Stackoverflow
Solution 16 - PythonChristoph BöddekerView Answer on Stackoverflow
Solution 17 - Pythondipenparmar12View Answer on Stackoverflow
Solution 18 - PythonPramod BhatView Answer on Stackoverflow
Solution 19 - PythonfullungView Answer on Stackoverflow
Solution 20 - PythonSuperNovaView Answer on Stackoverflow
Solution 21 - PythonxristianView Answer on Stackoverflow
Solution 22 - PythonKiwiView Answer on Stackoverflow