Skip to content

Instantly share code, notes, and snippets.

@dubpirate
Last active August 4, 2022 23:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dubpirate/fdea9a67500a46613ad637269320d272 to your computer and use it in GitHub Desktop.
Save dubpirate/fdea9a67500a46613ad637269320d272 to your computer and use it in GitHub Desktop.
Convert Pascal Case to Snake Case with Python and Regex.
import re
def to_snake(pascal:str) -> str:
"""Converts a Pascal case string to snake case.
"""
magic = re.findall('[A-Z]+[a-z]*', pascal)
snake = '_'.join(magic)
snake = snake.lower()
return snake
# Working examples:
assert to_snake("ID") == "id"
assert to_snake("HelloWorld") == "hello_world"
assert to_snake("EndsWithAllCapsXML") == "ends_with_all_caps_xml"
# Broken Examples:
assert to_snake("STARTINGWithAllCapsDoesntWork") == "startingwith_all_caps_doesnt_work"
assert to_snake("startingWithLowerCaseDoesntWork") == "with_lower_case_doesnt_work"
@dubpirate
Copy link
Author

I wrote this because the other regex examples I found in this StackOverflow question didn't capture the right scenarios, particularly ID to id, and a string ending with all caps (XML).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment