Skip to content

Fix/camel case to snake case #9778

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions strings/camel_case_to_snake_case.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import re


def camel_to_snake_case(input_str: str) -> str:
"""
Transforms a camelCase or PascalCase given string to snake_case

>>> camel_to_snake_case("someRandomString")
'some_random_string'

>>> camel_to_snake_case("SomeRandomString")
'some_random_string'

>>> camel_to_snake_case("someRandomStringWithNumbers123")
'some_random_string_with_numbers_123'

>>> camel_to_snake_case("SomeRandomStringWithNumbers123")
'some_random_string_with_numbers_123'

>>> camel_to_snake_case(123)
Traceback (most recent call last):
...
ValueError: Expected string as input, found <class 'int'>
"""

if not isinstance(input_str, str):
msg = f"Expected string as input, found {type(input_str)}"
raise ValueError(msg)

# Use regular expression to split words on capital letters and numbers
words = re.findall(r"[A-Z][a-z]*|\d+|[a-z]+", input_str)

# Join the words with underscores and convert to lowercase
return "_".join(words).lower()


if __name__ == "__main__":
from doctest import testmod

testmod()