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?
In Python, lower() is a built-in method used for string handling. The lower() method returns the lowercased string from the given string. It converts all uppercase characters to lowercase.
upper() Return Value upper() method returns the uppercase string from the given string. It converts all lowercase characters to uppercase. If no lowercase characters exist, it returns the original string.
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.
import re
"_".join(l.lower() for l in re.findall('[A-Z][^A-Z]*', 'ThisIsAGoodExample'))
EDIT: Actually, this only works, if the first letter is uppercase. Otherwise this (taken from here) does the right thing:
def convert(name):
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With