camel+snake

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: x.group(1).upper(), name)
 
def snake2camelback(name):
    return re.sub(r'_([a-z])', lambda x: x.group(1).upper(), name)
 
def camel2snake(name):
    return name[0].lower() + re.sub(r'(?!^)[A-Z]', lambda x: '_' + x.group(0).lower(), name[1:])
 
def camelback2snake(name):
    return re.sub(r'[A-Z]', lambda x: '_' + x.group(0).lower(), name)

Please find below explanations for each of those methods.

snake2camel

re.sub(r'(?:^|_)(\w)', lambda x: x.group(1).upper(), 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.

snake2camelback

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

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

camelback2snake

re.sub(r'[A-Z]', lambda x: '_' + x.group(0).lower(), 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.

camel2snake

name[0].lower() + re.sub(r'(?!^)[A-Z]', lambda x: '_' + x.group(0).lower(), 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


Warning: Unknown: open(/var/lib/php5/sessions/sess_ugvg2rj1mkvvkger396lc9aq70, O_RDWR) failed: Permission denied (13) in Unknown on line 0

Warning: Unknown: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/var/lib/php5/sessions) in Unknown on line 0