[boston-pig] Python syntax question
Ned Batchelder
ned at nedbatchelder.com
Tue Jun 5 06:12:52 MDT 2007
replace() is pretty simple. Generally if you need more than it does,
you have to jump up to re.sub(), or write your own. You don't mention
whether you want just the replacement to be case-magic:
"dog".myreplace("dog", "cat") --> "cat"
"Dog".myreplace("dog", "cat") --> "cat" or "Cat" ?
"DOG".myreplace("dog", "cat") --> "cat" or "CAT" ?
"DoG".myreplace("dog", "cat") --> "cat" or ?
If you want "cat" in all cases, re.sub will do the trick:
re.sub("(?i)dog", "cat", mystring)
If you want the magic replace, then you need more code:
import re
def magicreplace(str, old, new):
pattern = "(?i)" + re.escape(old)
def replfn(matchobj):
if matchobj.group(0).islower():
return new.lower()
elif matchobj.group(0).isupper():
return new.upper()
elif matchobj.group(0).istitle():
return new.title()
else:
return new
return re.sub(pattern, replfn, str)
assert magicreplace("my dog", "dog", "cat") == "my cat"
assert magicreplace("my Dog", "dog", "cat") == "my Cat"
assert magicreplace("my DOG", "dog", "cat") == "my CAT"
assert magicreplace("my DoG", "dog", "cat") == "my cat"
Hope this helps!
--Ned.
http://nedbatchelder.com/blog
Brook, Robert wrote:
>
>
> Does anyone know if there is a parameter I can set on the replace
> function that will do a case insensitive replace (old,new).
>
>
> Thanks in advance.
>
>
>
> Robert Brook
> Electric Insurance Company
> 75 Sam Fonzo Drive, Beverly, MA 01915
> phone: 978.524.5374
> fax: 978.236.5374
> robert.brook at electricinsurance.com
> http://www.electricinsurance.com
> <http://www.electricinsurance.com/>
>
>
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> boston-pig mailing list
> boston-pig at wingware.com
> http://wingware.com/mailman/listinfo/boston-pig
>
--
Ned Batchelder, http://nedbatchelder.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: /pipermail/boston-pig/attachments/20070605/2520a402/attachment.html
More information about the boston-pig
mailing list