Elegant Python function to convert CamelCase to snake_case?

Example:

>>> convert("CamelCase")
"camel_case"

Answer rating: 936




Camel case to snake case

import re

name = "CamelCaseName"
name = re.sub(r"(?<!^)(?=[A-Z])", "_", name).lower()
print(name)  # camel_case_name

If you do this many times and the above is slow, compile the regex beforehand:

pattern = re.compile(r"(?<!^)(?=[A-Z])")
name = pattern.sub("_", name).lower()

To handle more advanced cases specially (this is not reversible anymore):

def camel_to_snake(name):
  name = re.sub("(.)([A-Z][a-z]+)", r"1_2", name)
  return re.sub("([a-z0-9])([A-Z])", r"1_2", name).lower()

print(camel_to_snake("camel2_camel2_case"))  # camel2_camel2_case
print(camel_to_snake("getHTTPResponseCode"))  # get_http_response_code
print(camel_to_snake("HTTPResponseCodeXYZ"))  # http_response_code_xyz

To add also cases with two underscores or more:

def to_snake_case(name):
    name = re.sub("(.)([A-Z][a-z]+)", r"1_2", name)
    name = re.sub("__([A-Z])", r"_1", name)
    name = re.sub("([a-z0-9])([A-Z])", r"1_2", name)
    return name.lower()



Snake case to camel case

name = "snake_case_name"
name = "".join(word.title() for word in name.split("_"))
print(name)  # SnakeCaseName

Answer rating: 237

There"s an inflection library in the package index that can handle these things for you. In this case, you"d be looking for inflection.underscore():

>>> inflection.underscore("CamelCase")
"camel_case"




Get Solution for free from DataCamp guru