Last active
March 3, 2021 14:57
-
-
Save knu2xs/eb3c022433bf5fae8d1a963ff0f0ed5a to your computer and use it in GitHub Desktop.
Convert names from camel to snake case and vice versa.
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
snk1_re = re.compile(r'(.)([A-Z][a-z]+)') # single capital preceded by any character and followed by lowercase | |
snk2_re = re.compile('([a-z0-9])([A-Z])') # single capital preceded by lowercase or numeral | |
def to_snake(name:str): | |
assert isinstance(name, str) | |
nm1 = snk1_re.sub(r'\1_\2', name) | |
nm2 = snk2_re.sub(r'\1_\2', nm1).lower() | |
return nm2 | |
def to_camel(name:str): | |
assert isinstance(name, str) | |
nm = ''.join(word.title() if idx != 0 else word for idx, word in enumerate(name.split('_'))) | |
return nm |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment