Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save chekunkov/5998205 to your computer and use it in GitHub Desktop.
Save chekunkov/5998205 to your computer and use it in GitHub Desktop.
import re
def camelcase_to_lowercase_with_underscores(name):
"""
>>> camelcase_to_lowercase_with_underscores('CamelCase')
'camel_case'
>>> camelcase_to_lowercase_with_underscores('CamelCamelCase')
'camel_camel_case'
>>> camelcase_to_lowercase_with_underscores('Camel2Camel2Case')
'camel2_camel2_case'
>>> camelcase_to_lowercase_with_underscores('getHTTPResponseCode')
'get_http_response_code'
>>> camelcase_to_lowercase_with_underscores('get2HTTPResponseCode')
'get2_http_response_code'
>>> camelcase_to_lowercase_with_underscores('HTTPResponseCode')
'http_response_code'
>>> camelcase_to_lowercase_with_underscores('HTTPResponseCodeXYZ')
'http_response_code_xyz'
"""
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment