Elegant Python function to convert CamelCase to snake_case?
Data Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.
Converting strings from CamelCase to snake_case is a common requirement, especially when dealing with different programming languages or when preparing data for storage or transmission. In this article, we explore how to accomplish this in Python, providing a detailed explanation of an elegant solution using regular expressions.
Understanding the Problem
CamelCase is a naming convention where multiple words are joined together, and each word starts with an uppercase letter. For example: HelloWorld. In contrast, snake_case separates words using underscores and typically uses lowercase letters, such as: hello_world.
Python Solutions Using Regular Expressions
Regular expressions (regex) offer a powerful way to search and manipulate strings in Python. We can write a compact and efficient function to convert CamelCase to snake_case using Python's re module.
The Elegant Solution
Here's a Python function that performs the conversion:
re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name):- This pattern targets a lowercase letter followed by an uppercase letter at the start of a new word.
- The pattern
(.)([A-Z][a-z]+)captures two groups:(.)matches any character (the end of the previous word).([A-Z][a-z]+)matches an uppercase letter followed by one or more lowercase letters.
- The substitution
r'\1_\2'inserts an underscore between the two matched groups.
re.sub('([a-z0-9])([A-Z])', r'\1_\2', name):- This pattern targets the transition from lowercase/number to uppercase at the beginning of a new word.
- The pattern
([a-z0-9])([A-Z])captures two groups:([a-z0-9])matches a lowercase letter or digit.([A-Z])matches an uppercase letter.
- The substitution
r'\1_\2'also inserts an underscore between them.
- Converts the entire string to lowercase to match the snake_case convention.
- Single-word CamelCase: Non-CamelCase strings, such as
'Hello', remain unchanged. - Leading/Trailing Underscores: The function could be modified if underscores before or after the string are undesirable.
- Performance: The function, as written, performs well on typical strings. However, using compiled regex patterns with
re.compile()in cases of repeated conversions might enhance performance. - Maintaining Abbreviations: Modify the regex if you wish to preserve certain capitalizations (e.g.,
XMLHttpRequesttoxml_http_requestkeeping spelling asxmlHTTPRequest).
Related reading
- Elegant ways to support equivalence equality in Python classes
- Element-wise addition of 2 lists?
- elif in list comprehension conditionals
- Else clause on Python while statement
- Emacs bulk indent for Python
- Encrypt and decrypt using PyCrypto AES-256
- Ensemble of different kinds of regressors using scikit-learn or any other python framework
- EOFError Compressed file ended before the end-of-stream marker was reached - MNIST data set
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseNo course covers this one yet
Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.
Build my courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.