Last active
August 4, 2022 23:02
-
-
Save dubpirate/fdea9a67500a46613ad637269320d272 to your computer and use it in GitHub Desktop.
Convert Pascal Case to Snake Case with Python and Regex.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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).