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)
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)
|
This adds the problem of misinterpreting regex special characters:
You can avoid that with this pattern:
(Replace pat with pattern above, obviously.)
Mmh, I think the name is misleading.
str.replace(what, replacement, count) takes three arguments, substituting 'what' with 'replacement' up to 'count' times from the left, wherever 'what' lies in the original string.
Hence I'd think that "replace" whould just be your "lreplace", while "rreplace" would be a replace counting from right.
On the contrary, you're watching for a way to tell whether you should perform your substitution, and you've got a special case where the starting (or ending) pattern you want to check for is the very same you want to substitute. Otherwise I'd do something with startswith()/endswith() and string slicing, as D. Sutherland suggested.
BTW I think it's a special case enough to be dealt with regexps or custom funcs and not to stay in the standard lib.