Conversion between “CamelCase” and “snake_case” strings with Python

In some programs, it might be needed to convert strings between CamelCase, camelBack and snake_case notations. Here are a few function to perform these operations:

import re
def snake2camel(name):
    return re.sub(r'(?:^|_)([a-z])', lambda x:, name)
def snake2camelback(name):
    return re.sub(r'_([a-z])', lambda x:, name)
def camel2snake(name):
    return name[0].lower() + re.sub(r'(?!^)[A-Z]', lambda x: '_' +, name[1:])
def camelback2snake(name):
    return re.sub(r'[A-Z]', lambda x: '_' +, name)

Please find below explanations for each of those methods.


re.sub(r'(?:^|_)(\w)', lambda x:, name)
  • The regular expression looks for letters that are either at the beginning of the string, or preceded by an underscore. The given letter is captured.
  • Each of those occurences (undescore + letter) is replaced by the uppercase version of the found letter.


re.sub(r'_([a-z])', lambda x:, name)

This method works exactly as snake2camel, except that the first character is not taken into account for capitalization.


re.sub(r'[A-Z]', lambda x: '_' +, name)
  • The regular expression capture every capital letters in the given string.
  • For each of these groups, the character found is replaced by an underscore, followed by the lowercase version of the character.


name[0].lower() + re.sub(r'(?!^)[A-Z]', lambda x: '_' +, name[1:])

The conversion is very similar to the one performed in camelback2snake, except that the first character is processed out of the regular expression.

Leave a Comment