How to replace upper case with underscore?

I am new to Python and I am trying to replace all capital letters in a word to emphasize, for example:

ThisIsAGoodExample 

should become

 this_is_a_good_example 

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

+7
source share
6 answers

The regex is used here:

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

This says: β€œFind the points in the line that does not precede the beginning of the line, and it is followed by the uppercase character and substitute the underscore. Then we omit () the whole thing.

+10
source
 import re "_".join(l.lower() for l in re.findall('[AZ][^AZ]*', '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('(.)([AZ][az]+)', r'\1_\2', name) return re.sub('([a-z0-9])([AZ])', r'\1_\2', s1).lower() 
+8
source

This generates a list of elements, where each element is "_" followed by a lowercase letter if the character was originally an uppercase letter or the character itself if it is not. Then it combines them together into a string and removes all leading underscores that can be added by the process:

 print ''.join('_' + char.lower() if char.isupper() else char for char in inputstring).lstrip('_') 

By the way, you did not specify what to do with underscores that are already present in the line. I was not sure how to handle this, so I lost.

+4
source
 example = 'ThisIsAGoodExample' # Don't put an underscore before first character. new_example = example[0] for character in example[1:]: # Append an underscore if the character is uppercase. if character.isupper(): new_example += '_' new_example += character.lower() 
+2
source

Since no one else has proposed a solution using a generator, here is one:

 >>> sample = "ThisIsAGoodExample" >>> def upperSplit(data): ... buff = '' ... for item in data: ... if item.isupper(): ... if buff: ... yield buff ... buff = '' ... buff += item ... yield buff ... >>> list(upperSplit(sample)) ['This', 'Is', 'A', 'Good', 'Example'] >>> "_".join(upperSplit(sample)).lower() 'this_is_a_good_example' 
+1
source

Parse a string, every time you encounter a letter in upper case, insert _ in front of it and then switch the found character to lower case

0
source

All Articles