How to replace uppercase with underscore?

TiGer picture TiGer · Sep 6, 2011 · Viewed 12.9k times · Source

I'm new to Python and I am trying to replace all uppercase-letters within a word to underscores, for example:

ThisIsAGoodExample

should become

this_is_a_good_example

Any ideas/tips/links/tutorials on how to achieve this?

Answer

Kris Jenkins picture Kris Jenkins · Sep 6, 2011

Here's a regex way:

import re
example = "ThisIsAGoodExample"
print re.sub( '(?<!^)(?=[A-Z])', '_', example ).lower()

This is saying, "Find points in the string that aren't preceeded by a start of line, and are followed by an uppercase character, and substitute an underscore. Then we lower()case the whole thing.