Last active
April 20, 2021 16:17
-
-
Save ultrafunkamsterdam/112cf56be0b2cfafb0fa430690512aae to your computer and use it in GitHub Desktop.
Python convert snake_case to camelCase and camelCase to snake_case
This file contains hidden or 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
""" | |
██████╗ █████╗ ███╗ ███╗███████╗██╗ ███████╗███╗ ██╗ █████╗ ██╗ ██╗███████╗ | |
██╔════╝██╔══██╗████╗ ████║██╔════╝██║ ██╔════╝████╗ ██║██╔══██╗██║ ██╔╝██╔════╝ | |
██║ ███████║██╔████╔██║█████╗ ██║ ███████╗██╔██╗ ██║███████║█████╔╝ █████╗ | |
██║ ██╔══██║██║╚██╔╝██║██╔══╝ ██║ ╚════██║██║╚██╗██║██╔══██║██╔═██╗ ██╔══╝ | |
╚██████╗██║ ██║██║ ╚═╝ ██║███████╗███████╗███████║██║ ╚████║██║ ██║██║ ██╗███████╗ | |
╚═════╝╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚══════╝╚══════╝╚═╝ ╚═══╝╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝ | |
github.com/UltrafunkAmsterdam | |
""" | |
import re | |
RE_CAMEL_TO_SNAKE = re.compile("((?!^)(?<!_)[A-Z][a-z]+|(?<=[a-z0-9])[A-Z])") | |
RE_SNAKE_TO_CAMEL = re.compile("(.*?)_([a-zA-Z])") | |
def camel_to_snake(s): | |
""" | |
Converts CamelCase/camelCase to snake_case | |
:param str s: string to be converted | |
:return: (str) snake_case version of s | |
""" | |
return RE_CAMEL_TO_SNAKE.sub(r"_\1", s).lower() | |
def snake_to_camel(s): | |
""" | |
Converts snake_case_string to camelCaseString | |
:param str s: string to be converted | |
:return: (str) camelCase version of s | |
""" | |
return RE_SNAKE_TO_CAMEL.sub(lambda m: m.group(1) + m.group(2).upper(), s, 0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment