Skip to content

Commit

Permalink
Merge pull request #417 from bjeffrey92/to-snake-with-digits
Browse files Browse the repository at this point in the history
optionally treat digits as capitals when converting to snake case
  • Loading branch information
sanders41 authored Oct 26, 2023
2 parents 17035e5 + 0657a9a commit 066006c
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 9 deletions.
16 changes: 13 additions & 3 deletions camel_converter/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,16 +111,26 @@ def to_camel(snake_string: str) -> str:


@lru_cache(maxsize=4096)
def to_snake(camel_string: str) -> str:
def to_snake(camel_string: str, *, treat_digits_as_capitals: bool = False) -> str:
"""Converts a camel case or pascal case string to snake case.
Args:
camel_string: String in camel case or pascal case format. For example myVariable.
camel_string:
String in camel case or pascal case format. For example myVariable.
treat_digits_as_capitals:
Whether to treat digits as capitals. For example myVariable2 would become my_variable_2 rather than my_variable2.
Returns:
The string in snake case format. For example my_variable.
"""
return "".join([f"_{c}" if c.isupper() else c for c in camel_string]).lstrip("_").lower()

def check_character(c: str) -> str:
if c.isupper() or (treat_digits_as_capitals and c.isdigit()):
return f"_{c}"
else:
return c

return "".join([check_character(c) for c in camel_string]).lstrip("_").lower()


@lru_cache(maxsize=4096)
Expand Down
14 changes: 8 additions & 6 deletions tests/test_camel_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,12 +146,14 @@ def test_to_pascal(test_str, expected_str):


@pytest.mark.parametrize(
"test_str, expected_str",
"test_str, expected_str, treat_digits_as_capitals",
[
("thisIsATest", "this_is_a_test"),
("ThisIsATest", "this_is_a_test"),
("aTestWith12Number", "a_test_with12_number"),
("thisIsATest", "this_is_a_test", False),
("ThisIsATest", "this_is_a_test", False),
("aTestWith12Number", "a_test_with12_number", False),
("aTestWith12Number", "a_test_with_1_2_number", True),
("ATestWith12Number", "a_test_with_1_2_number", True),
],
)
def test_to_snake(test_str, expected_str):
assert to_snake(test_str) == expected_str
def test_to_snake(test_str, expected_str, treat_digits_as_capitals):
assert to_snake(test_str, treat_digits_as_capitals=treat_digits_as_capitals) == expected_str

0 comments on commit 066006c

Please sign in to comment.