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

How to Convert CamelCase to Snake_case in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-28 05:38:30359browse

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

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

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

>>> convert('CamelCase')
'camel_case'

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!

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