w3resource

Python: Convert camel case string to snake case string


Write a Python program to convert a camel-case string to a 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                                                                                              

Pictorial Presentation:

Python: Regular Expression - Convert camel case string to snake case string.

Flowchart:

Flowchart: Regular Expression - Convert camel case string to snake case string.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to find all words which are at least 4 characters long in a string.
Next: Write a python program to convert snake case string to camel case string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.