w3resource logo
Python Exercises

Python: Convert camel case string to snake case string

Python Regular Expression: Exercise-36 with Solution

Write a python program to convert camel case string to snake case string.

Sample Solution:-

Python Code:

def camel_to_snake(text):
        import re
        str1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', text)
        return re.sub('([a-z0-9])([A-Z])', r'\1_\2', str1).lower()

print(camel_to_snake('PythonExercises'))

Sample Output:

python_exercises                                                                                              

Python Code Editor:

def camel_to_snake(text):
        import re
        str1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', text)
        return re.sub('([a-z0-9])([A-Z])', r'\1_\2', str1).lower()

print(camel_to_snake('PythonExercises'))

Improve this sample solution and post your code through Disqus