Created
July 27, 2023 11:37
-
-
Save atemate/c3a4141fcf0541c7af9e86f834ace9d7 to your computer and use it in GitHub Desktop.
Converts camel case to snake case
This file contains 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
# 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("_") |
This file contains 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
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