Last active
July 11, 2024 14:41
-
-
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
Careful with this implementation, one would assume to_snake() to be idempotent, but
to_snake("already_snake") == ''
.Don't shoot yourself in the foot here. You can find an improved version below. It handles idempotency, uppercases and camel cases correctly (afaik).
👁️ I'm unaware that lower case letters should be discarded when converting from PascaslCase to snake_case, i. e.
assert to_snake("startingWithLowerCaseDoesntWork") == "with_lower_case_doesnt_work"
- so the below implementation does NOT do that