Python: How can I replace text in a string when the case of the text differs?

I process a lot of paths. Some of these paths are entered by hand, by a human. Other paths are machine generated by some tool. Sometimes the tool will respect the case entered originally, other times it makes everything lowercase. Based on these combinations, you could be dealing with two paths that are the exact same (location on disk), but some have upper-case characters defining part of their name, and others, lower-case text. If you need to process these paths, and change them from one relative path to another, these case inconsistencies can become a real pain. Below is one solution around the issue. I’d be interested to see others :)

Using re.findall, we can search in a string. But what really helps is re.IGNORECASE. This gives us a matching string based on the case of the source string, which we can then use to replace with later using the .replace() string method:

import re

srcPath ="c:/my/path/wIth/mIxeD/case"
match = "/with/mixed/"
replace = "/normal/"
resultPath = ""

try:
    sourceCaseMatch = re.findall(match, srcPath, re.IGNORECASE)[0]
    resultPath = srcPath.replace(sourceCaseMatch, replace)
except:
    pass

print "Result: '" + resultPath + "'"
# Result: 'c:/my/path/normal/case'

This is also posted on my Python Wiki

Understading Python generators in Maya
What to make a game in?
  • Trackback are closed
  • Comments (5)
    • mark
    • April 15th, 2009 10:54am

    Incredible site!

    • Yulia
    • May 26th, 2009 1:01pm

    Hi, I’m a beginner at Python, what I need is to replace in xml page everything between and , or everything that starts with src= and ends ( at the end of the actual link ) “, with
    some other string.
    How can I do it with RE?

    thanks a lot for the answer

  1. I’m sure you could use re, but you’d be better off using something like ElementTree to actually parse the xml directly, and reformat it. Since it’s xml, it makes sense (to me) to actually make Python do the work for you. I have some notes on my Python wiki here for ElementTree:
    http://pythonwiki.tiddlyspot.com/#%5B%5BWorking%20with%20xml%20and%20ElementTree%5D%5D
    Here’s the direct link to two document pages on it:
    http://docs.python.org/library/xml.etree.elementtree.html
    http://effbot.org/zone/element.htm
    You could also use something like minidom, but I find it really clunky compared to ElementTree.

    • siri
    • April 3rd, 2017 4:20am

    how to convert number to word in python program, I am beginner to learn

  2. num = 23.5
    word = str(num)

    Pretty easy 😉

Comment are closed.