Last Updated: February 25, 2016
·
1.222K
· boblefrag

Convert camelcase string into underscored one

def camel_to_underscore(string):
    """
    Convert a CamelCased string into an underscored one
    Usage :
    >>> camel_to_underscore("ThisIsATest")
    this_is_a_test
    """
    list_string = []
    for c in string[1:]:
        if c.isupper():
            list_string.append("_" + c.lower())
        else:
            list_string.append(c)
    return string[0].lower() + ''.join(list_string)

1 Response
Add your response


import re
def cameltounderscore(string):
def repl(match): return '_%s' % match.group(0).lower()
return re.sub('[A-Z]', repl, string)[1:]
</pre>
over 1 year ago ·