re.sub(r'(?<=\w)(; )', r'_\1', text).lower()
String & Text Processing

Meaning

Converts CamelCase or PascalCase strings to snake_case by inserting an underscore before uppercase letters that follow a word character, then lowercasing the entire string. Use this when normalizing identifiers for Python conventions or preparing data for serialization.

Primary Function

String transformation

Communicative Purpose

Standardizes identifier naming conventions from CamelCase to snake_case.

Pattern

re.sub(r'(?<=\\w)([A-Z])', r'_\\1', text).lower()

Core Structure

re.sub(r'(?<=\\w)([A-Z])', r'_\\1', ...).lower()

Função primária

String transformation

Propósito comunicativo

Standardizes identifier naming conventions from CamelCase to snake_case.

Situações de gatilho

API integration: converting JavaScript CamelCase response keys to Python snake_case Code refactoring: renaming imported variable names from other languages to snake_case Database schema migration: normalizing column names generated from class names

Contextos

Data cleaning scripts, ORM model definitions, API integration layers, refactoring tools.

Padrão

re.sub(r'(?<=\\w)([A-Z])', r'_\\1', text).lower()

Estrutura central

re.sub(r'(?<=\\w)([A-Z])', r'_\\1', ...).lower()

Slots de substituição

text: the input string variable

Colocados típicos

  • Commonly used with import re
  • string stripping methods like .strip()
  • and replacement methods like .replace().

Substituições comuns

  • Using a loop with char.isupper() checks – more readable but slower for large strings
  • using the third‑party 'regex' library for better Unicode support – adds dependency but handles complex Unicode cases.

Erros comuns

Forgetting the lookbehind (?<=\\w) which places an underscore before the first character of PascalCase (e.g., '_UserProfile') causing a leading underscore. Omitting the .lower() call, leaving uppercase letters and producing Mixed_case output instead of snake_case. Using the pattern without the lookbehind and applying it to strings that start with an uppercase letter, resulting in an unwanted leading underscore.

Similar / contraste

str.lower() alone – only lowercases letters, does not insert underscores. re.sub(r'([a-z])([A-Z])', r'\\1_\\2', text).lower() – alternative capture‑group approach that works similarly but requires two capturing groups. re.sub(r'([A-Z]+)', r'_\\1', text).lower() – naive acronym handling that incorrectly splits each uppercase letter.

Interferências

Coming from JavaScript: developers might manually split/join strings instead of using a single regex pass – leads to more verbose code and missed edge cases.

Família do chunk

  • snake_case conversion
  • CamelCase splitting
  • regex lookarounds

Nuance

Avoid using this pattern when the input may contain consecutive uppercase letters (acronyms) because it splits each letter, producing 'x_m_l_parser' from 'XMLParser'; performance impact is negligible for typical identifier lengths but the regex scans the whole string; boundary case: strings that start with an uppercase letter will get a leading underscore if the lookbehind is omitted.

Efeito pragmático

Ensures code adheres to PEP 8 naming standards automatically.

Dica de memória

Lookbehind for word, capture Upper, prepend underscore, then lower all.

Nota

This pattern does not handle consecutive uppercase letters (acronyms) ideally; e.g., 'XMLParser' yields 'x_m_l_parser'. For better acronym handling, consider patterns that treat sequences of uppercase as a single word.

Upgrade path

re.sub(r'(?<!^)(?=[A-Z])', '_', text).lower() for better acronym handling (though still imperfect for all cases), or using external libraries like 'inflection'.

Frequência: HighFormulaicidade: FixedTipo de construção: regex substitution with lookbehind and backreferencePrioridade de aquisição: Active recallPrioridade de output: BothTag de espaçamento: Medium-termIdioma?: Sim

Log in to save chunks.