Tuesday 11 February 2020

LREPLACE() AND RREPLACE(): REPLACE THE BEGINNING AND ENDS OF A STRINGS (PYTHON RECIPE)

Python newbies will often make the following mistake (I certainly have =):
>>> test = """this is a test:
... tis the season for mistakes."""
>>> for line in test.split('\n'):
...     print line.lstrip('this')
... 
 is a test
 the season for mistakes.
The mistake is assuming that lstrip() (or rstrip()) strips a string (whole) when it actually strips all of the provided characters in the given string. Python actually comes with no function to strip a string from the left-hand or right-hand side of a string so I wrote this (very simple) recipe to solve that problem. Here's the usage:
>>> test = """this is a test:
... tis the season for mistakes."""
>>> for line in test.split('\n'):
...     print lreplace('this', '', line)
... 
 is a test
tis the season for mistakes.
I really wish Python had these functions built into the string object. I think it would be a useful addition to the standard library. It would also be nicer to type this:
line.lreplace('this', '')
Instead of this:
lreplace('this','',line)
Python, 13 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import re

def lreplace(pattern, sub, string):
    """
    Replaces 'pattern' in 'string' with 'sub' if 'pattern' starts 'string'.
    """
    return re.sub('^%s' % pattern, sub, string)

def rreplace(pattern, sub, string):
    """
    Replaces 'pattern' in 'string' with 'sub' if 'pattern' ends 'string'.
    """
    return re.sub('%s$' % pattern, sub, string)

from : http://code.activestate.com/recipes/577252-lreplace-and-rreplace-replace-the-beginning-and-en/

No comments:

Post a Comment