Welcome, guest | Sign In | My Account | Store | Cart

These short functions convert identifier names between the most common naming conventions: CapitalizedWords, mixedCase and under_scores.

Python, 27 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import re

def cw2us(x): # capwords to underscore notation
    return re.sub(r'(?<=[a-z])[A-Z]|(?<!^)[A-Z](?=[a-z])', r"_\g<0>", x).lower()

def mc2us(x): # mixed case to underscore notation
    return cw2us(x)

def us2mc(x): # underscore to mixed case notation
    return re.sub(r'_([a-z])', lambda m: (m.group(1).upper()), x)

def us2cw(x): # underscore to capwords notation
    s = us2mc(x)
    return s[0].upper()+s[1:]

##
## Expected output:
##
## >>> cw2us("PrintHTML")
## 'print_html'
## >>> cw2us("IOError")
## 'io_error'
## >>> cw2us("SetXYPosition")
## 'set_xy_position'
## >>> cw2us("GetX")
## 'get_x'
##