Home Backend Development Python Tutorial How to Convert CamelCase to snake_case in Python Elegantly?

How to Convert CamelCase to snake_case in Python Elegantly?

Nov 01, 2024 pm 10:12 PM

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:

1

2

3

4

5

<code class="python">import re

 

def camel_to_snake(name):

    name = re.sub(r'(?&lt;!^)(?=[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:

1

2

<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:

1

2

<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:

1

2

3

<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:

1

2

3

<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!

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

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How Do I Use Beautiful Soup to Parse HTML? How Do I Use Beautiful Soup to Parse HTML? Mar 10, 2025 pm 06:54 PM

How Do I Use Beautiful Soup to Parse HTML?

How to Download Files in Python How to Download Files in Python Mar 01, 2025 am 10:03 AM

How to Download Files in Python

Image Filtering in Python Image Filtering in Python Mar 03, 2025 am 09:44 AM

Image Filtering in Python

How to Use Python to Find the Zipf Distribution of a Text File How to Use Python to Find the Zipf Distribution of a Text File Mar 05, 2025 am 09:58 AM

How to Use Python to Find the Zipf Distribution of a Text File

How to Work With PDF Documents Using Python How to Work With PDF Documents Using Python Mar 02, 2025 am 09:54 AM

How to Work With PDF Documents Using Python

How to Cache Using Redis in Django Applications How to Cache Using Redis in Django Applications Mar 02, 2025 am 10:10 AM

How to Cache Using Redis in Django Applications

How to Perform Deep Learning with TensorFlow or PyTorch? How to Perform Deep Learning with TensorFlow or PyTorch? Mar 10, 2025 pm 06:52 PM

How to Perform Deep Learning with TensorFlow or PyTorch?

Introducing the Natural Language Toolkit (NLTK) Introducing the Natural Language Toolkit (NLTK) Mar 01, 2025 am 10:05 AM

Introducing the Natural Language Toolkit (NLTK)

See all articles