Skip to content

Instantly share code, notes, and snippets.

@knu2xs
Last active March 3, 2021 14:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save knu2xs/eb3c022433bf5fae8d1a963ff0f0ed5a to your computer and use it in GitHub Desktop.
Save knu2xs/eb3c022433bf5fae8d1a963ff0f0ed5a to your computer and use it in GitHub Desktop.
Convert names from camel to snake case and vice versa.
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