Skip to content

Instantly share code, notes, and snippets.

@cameronp98
Created January 9, 2014 22:01
Show Gist options
  • Save cameronp98/8342877 to your computer and use it in GitHub Desktop.
Save cameronp98/8342877 to your computer and use it in GitHub Desktop.
Convert CamelCase to snake_case in Python
import re
def convert(name):
s1 = re.sub(r"(.)([A-Z][a-z]+)", r"\1_\2", name)
return re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", s1).lower()
tests = ["CamelCase", "CamelCamelCase", "getHTTPResponseCode",
"getHTTPResponseCode", "HTTPResponseCodeXYZ"]
for test in tests:
print(test, "=>", convert(test))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment