Skip to content

Fixes #9726 Convert Camel case t0 Snake Case #9828

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
wants to merge 4 commits into from
Closed
Changes from 1 commit
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
42 changes: 42 additions & 0 deletions strings/camel_case_to_snake_case.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
def camel_to_snake(camel_str : str) -> str :
import re

"""
>>> camel_to_snake('someRandomStringWithNumbers123')
'some_random_string_with_numbers_1_2_3'
>>> camel_to_snake('someRandomString')
'some_random_string'
>>> camel_to_snake(123)
Traceback (most recent call last):
...
ValueError: Expected string as input, found <class 'int'>

"""


# Raises an error if the input is not a string
if not isinstance(camel_str, str):
msg = f"Expected string as input, found {type(camel_str)}"
raise ValueError(msg)

""" Use regular expressions to find all occurrences of capital letters
followed by lowercase letters or digits. """
pattern = re.compile(r'(?<=[a-z0-9])([A-Z0-9])')

# Replace the capital letter or digit with an underscore and the lowercase version.
snake_str = re.sub(pattern, r'_\1', camel_str)

# Convert the result to lowercase to get snake_case
snake_str = snake_str.lower()

# If the string starts with a capital letter, add an underscore at the beginning.
if camel_str[0].isupper():
snake_str = '_' + snake_str

return snake_str


if __name__ == "__main__" :
import doctest

doctest.testmod()