Home  >  Article  >  Backend Development  >  How to efficiently convert CamelCase to snake_case in Python?

How to efficiently convert CamelCase to snake_case in Python?

Susan Sarandon
Susan SarandonOriginal
2024-10-28 00:20:29220browse

How to efficiently convert CamelCase to snake_case in Python?

CamelCase to snake_case Conversion 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.

Proposed Solution

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.

Alternative Approaches

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()

Snake_case to PascalCase Conversion

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn