Skip to content

Instantly share code, notes, and snippets.

@yjcrocks
Last active September 13, 2018 10:41
Show Gist options
  • Save yjcrocks/2f4cc3cf9bfac737c2efc41559a6847c to your computer and use it in GitHub Desktop.
Save yjcrocks/2f4cc3cf9bfac737c2efc41559a6847c to your computer and use it in GitHub Desktop.
camel case to snake case, snake case to camel case
# https://stackoverflow.com/questions/1175208/elegant-python-function-to-convert-camelcase-to-snake-case
camel_re_check = re.compile(r"^(?:[A-Z][a-z]*)+$")
camel_re_substitute = re.compile(r"((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))")
is_camel = lambda x: bool(camel_re_check.match(x))
camel_to_snake = lambda x: camel_re_substitute.sub(r"_\1", x).lower()
# https://stackoverflow.com/questions/4303492/how-can-i-simplify-this-conversion-from-underscore-to-camelcase-in-python
snake_re_check = re.compile(r"((^|_+)[a-z0-9]*)*$")
snake_re_substitute = re.compile(r"(?!^)_([a-zA-Z])")
is_snake = lambda x: bool(snake_re_check.match(x))
snake_to_camel = lambda x: snake_re_substitute.sub(lambda m: m.group(1).upper(), x)
In [2]: camel_to_snake("getHTTPRequest")
Out[2]: 'get_http_request'
In [3]: snake_to_camel("get_http_request")
Out[3]: 'getHttpRequest'
In [4]: snake_to_camel("__get_context")
Out[4]: '_GetContext'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment