Home > Backend Development > Python Tutorial > How to Convert CamelCase to Snake_case in Python?

How to Convert CamelCase to Snake_case in Python?

Mary-Kate Olsen
Release: 2024-10-28 05:38:30
Original
475 people have browsed it

How to Convert CamelCase to Snake_case in Python?

Convert CamelCase to snake_case

CamelCase and snake_case are two common naming conventions used in programming. CamelCase is often used for class and method names, while snake_case is used for variable and function names.

There are many ways to convert between these two naming conventions. One simple way is to use a regular expression. The following regular expression will match any uppercase letter that is preceded by a lowercase letter:

(?<=[a-z])(?=[A-Z])
Copy after login

Once we have a regular expression that can match the uppercase letters, we can replace them with an underscore. The following code shows how to do this:

import re
pattern = re.compile(r'(?<=[a-z])(?=[A-Z])')
name = pattern.sub('_', name)
name = name.lower()
Copy after login

Here's an example of how to use this function:

>>> convert('CamelCase')
'camel_case'
Copy after login

The above is the detailed content of How to Convert CamelCase to Snake_case in Python?. 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