Elegant Python function to convert CamelCase to snake_case?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
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 courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.