Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace uppercase with underscore?

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?

like image 333
TiGer Avatar asked Sep 06 '11 15:09

TiGer


People also ask

How do you change uppercase letters in python?

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.

How do I convert lowercase to uppercase in Python?

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.


2 Answers

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.

like image 115
Kris Jenkins Avatar answered Sep 29 '22 08:09

Kris Jenkins


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()
like image 35
xubuntix Avatar answered Sep 29 '22 09:09

xubuntix