Skip to content

Instantly share code, notes, and snippets.

@atemate
Created July 27, 2023 11:37
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 atemate/c3a4141fcf0541c7af9e86f834ace9d7 to your computer and use it in GitHub Desktop.
Save atemate/c3a4141fcf0541c7af9e86f834ace9d7 to your computer and use it in GitHub Desktop.
Converts camel case to snake case
# Kudos to: https://stackoverflow.com/a/12867228
def camel_to_snake(value: str) -> str:
"""
Converts value in camel case to snake case:
>>> camel_to_snake("camelCase")
'camel_case'
>>> camel_to_snake("PascalCase")
'pascal_case'
>>> camel_to_snake("one1Two2Three")
'one1_two2_three'
>>> camel_to_snake("getHTTPResponseCode")
'get_httpresponse_code'
"""
return re.sub("([A-Z]+)", r"_\1", value).lower().strip("_")
import pytest
from camel_to_snake import camel_to_snake
@pytest.mark.parametrize(
"input, expected",
[
("camelCase", "camel_case"),
("PascalCase", "pascal_case"),
("one1Two2Three", "one1_two2_three"),
("getHTTPResponseCode", "get_httpresponse_code"),
("", ""),
("123", "123"),
("123camelCase", "123camel_case"),
("123Kekeke", "123_kekeke"),
],
)
def test_camel_to_snake(input, expected):
assert camel_to_snake(input) == expected
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment