w3resource

Python: Convert camel case string to snake case string

Python Regular Expression: Exercise-36 with Solution

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/re/python-re-exercise-36.php