How to Convert CamelCase to snake_case in Python Elegantly?

Barbara Streisand
Release: 2024-11-01 22:12:31
Original
626 people have browsed it

How to Convert CamelCase to snake_case in Python Elegantly?

Elegant Python function to convert CamelCase to snake_case?

Converting from CamelCase to snake_case in Python requires a simple yet elegant approach. This article explores several effective methods to achieve this transformation, addressing variations in naming conventions and providing clear examples.

Using Regular Expressions with Lookahead/Lookbehind

The most versatile method utilizes regular expressions with lookahead and lookbehind assertions:

<code class="python">import re

def camel_to_snake(name):
    name = re.sub(r'(?<!^)(?=[A-Z])', '_', name).lower()
    return name</code>
Copy after login

This pattern matches boundaries between uppercase and lowercase characters, inserting underscores while simultaneously converting to lowercase.

Alternative Regex Patterns

For more complex cases, here's an alternative regex with alternation:

<code class="python">pattern = re.compile(r"(\w+)([A-Z]\w+)")
name = "_".join(pattern.findall(name))</code>
Copy after login

This pattern handles cases where multiple uppercase letters appear consecutively.

To avoid converting "HTTPHeader" to "h_t_t_p_header," use the following pattern:

<code class="python">pattern = re.compile(r"([a-z])([A-Z])")
name = "_".join(pattern.findall(name))</code>
Copy after login

Multi-Pass Substitutions

An alternative approach avoids using lookahead/lookbehind:

<code class="python">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()</code>
Copy after login

This approach combines two substitution passes to handle various naming conventions.

Snake Case to Pascal Case

For completeness, here's a function to convert snake_case to PascalCase:

<code class="python">def snake_to_pascal(name):
    name = ''.join(word.title() for word in name.split('_'))
    return name</code>
Copy after login

These functions provide a comprehensive solution to CamelCase and snake_case transformations in Python, catering to various naming conventions.

The above is the detailed content of How to Convert CamelCase to snake_case in Python Elegantly?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template