Posts Tagged ‘ path

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