Home >Backend Development >Python Tutorial >How to efficiently convert CamelCase to snake_case in Python?
The conversion from CamelCase to snake_case is a frequent transformation in Python programming. This question focuses on finding an efficient way to perform this task.
The provided code utilizes the re module to achieve this conversion:
import re
name = 'CamelCaseName'
name = re.sub(r'(?print(name) # camel_case_name
This code employs a regular expression to insert underscores before capital letters, and then converts the resulting string to lowercase. The result is the desired snake_case representation.
If performance is a concern, the regex can be compiled beforehand:
pattern = re.compile(r'(?name = pattern.sub('_', name).lower()
For more advanced cases, a double substitution pass can be used:
def camel_to_snake(name):
name = re.sub('(.)([A-Z][a-z]+)', r'_', name) return re.sub('([a-z0-9])([A-Z])', r'_', name).lower()
Furthermore, the code can be extended to handle multiple underscores:
def to_snake_case(name):
name = re.sub('(.)([A-Z][a-z]+)', r'_', name) name = re.sub('__([A-Z])', r'_', name) name = re.sub('([a-z0-9])([A-Z])', r'_', name) return name.lower()
Additionally, a reverse conversion from snake_case to PascalCase is provided:
name = 'snake_case_name'
name = ''.join(word.title() for word in name.split('_'))
print(name) # SnakeCaseName
The above is the detailed content of How to efficiently convert CamelCase to snake_case in Python?. For more information, please follow other related articles on the PHP Chinese website!