w3resource

Python: Convert camel case string to snake case string


36. Camel to Snake

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.

For more Practice: Solve these Related Problems:

  • Write a Python program to convert a camelCase string to snake_case using regex.
  • Write a Python script to transform a camelCase identifier into snake_case and then print the result.
  • Write a Python program to process multiple camelCase strings and convert each to snake_case.
  • Write a Python function to detect camelCase strings in a list and convert them to snake_case.

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.