CamelCase to snake_case: python

Ebates Coupons and Cash Back


Given a value that’s in CamelCase (like a Java Variable Name pattern), and you want to change it to snake_case (python, perl, and maybe other scripting languages), here is the python function to do it.

def to_snake_case(given_value):
    import re
    s = re.compile('([A-Z])')
    return s.sub(r'_\1', given_value).lower().replace('__', '_').lstrip('_')

print(to_snake_case1(‘CamelCase’))
print(to_snake_case1(‘camelcase’))
print(to_snake_case1(‘CCamAAelCase’))
print(to_snake_case1(‘CCamel_Case’))

camel_case
camelcase
c_cam_a_ael_case
c_camel_case

If you want the Consecutive Capital Letters to be kept as one group, then a slight modification of the function will do.

def to_snake_case1(given_value):
    import re
    s = re.compile('([A-Z]+)')
    return s.sub(r'_\1', given_value).lower().replace('__', '_').lstrip('_')

print(to_snake_case1(‘CamelCase’))
print(to_snake_case1(‘camelcase’))
print(to_snake_case1(‘CCamAAelCase’))
print(to_snake_case1(‘CCamel_Case’))

camel_case
camelcase
ccam_aael_case
ccamel_case

If you want to give a list/array of values, and return all the values changed to snake case, here’s the modified function.

def to_snake_case(given_list):
    import re
    s = re.compile('([A-Z]+)')
    result = []
    for e in given_list:
        result.append(b.sub(r'_\1', e).lower().replace('__', '_').lstrip('_'))
    return result

print(to_snake_case2([‘CamelCase’, ‘camelcase’, ‘CCamAAelCase’, ‘CCamel_Case’]))

[‘camel_case’, ‘camelcase’, ‘ccam_aael_case’, ‘ccamel_case’]


Ebates Coupons and Cash Back

 

One thought on “CamelCase to snake_case: python

  1. Hello,

    10/10 !!! Thank you for making your blogs an embodiment of perfection and simplicity. You make everything so easy to follow.

    New here and to Python and I’m just wondering about some possiblities.

    I like to learn by doing and am looking to start working on an application. I usually can research well for problems using google as long as I have the questions and they are not too broad. For now my wonderings are broad. I’m hoping someone can point me in a direction so I can focus on it. Also hope this is the right section for general questions…


    Can I do this with Python?

    I want to create an application which is time related, where points in time are recorded and then at the end of the given ammount of time data is outputed with that information.
    An example: I have a video which is of a 1000 meters race. I start my appliction at the beginning of the race. As each runner crosses the finish line I hit a key/mouse click. When the last runner crosses the line I stop the application. Can I then have data which has these points plotted in time in it?

    Super likes !!! for this amazing post. I thinks everyone should bookmark this.

    Many Thanks,
    Ajeeth

    Like

Leave a comment