text.swapcase()
String & Text Processing

Meaning

Returns a new string with uppercase characters converted to lowercase and lowercase characters converted to uppercase. Non‑alphabetic characters are left unchanged. It is useful when you need to invert the case of a string for display or comparison.

Primary Function

String manipulation

Communicative Purpose

Invert the case of each alphabetic character in a string.

Pattern

; .swapcase()

Core Structure

; .swapcase()

Função primária

String manipulation

Propósito comunicativo

Invert the case of each alphabetic character in a string.

Situações de gatilho

Preparing user input for case‑insensitive matching; creating a simple visual effect by flipping case; generating a transformed version of a string for testing case‑sensitive code.

Contextos

Any Python program that works with strings; standard library scripts, data cleaning, UI text generation.

Padrão

; .swapcase()

Estrutura central

; .swapcase()

Slots de substituição

string_expression: any expression that evaluates to a string (variable, literal, or function call).

Colocados típicos

  • str.upper()
  • str.lower()
  • str.title()
  • str.strip()

Substituições comuns

  • Using a comprehension: ''.join(c.lower() if c.isupper() else c.upper() for c in s)
  • or str.translate with a custom translation table.

Erros comuns

Assuming the method modifies the original string (strings are immutable); applying it to non‑string objects without conversion; expecting it to affect non‑alphabetic characters.

Similar / contraste

str.upper() (makes all characters uppercase); str.lower() (makes all lowercase); str.capitalize() (capitalizes first character only).

Interferências

Coming from languages with mutable character arrays (e.g., C): may expect in‑place modification; remember that Python strings are immutable and swapcase() returns a new string.

Família do chunk

  • string case conversion methods
  • string transformation methods

Nuance

The transformation follows Unicode case mapping rules and is locale‑independent; symbols, digits, and punctuation remain unchanged; the result length equals the input length.

Efeito pragmático

Provides a quick, readable way to invert case without explicit loops or conditionals.

Dica de memória

Think of 'swap' as swapping hats: uppercase ↔ lowercase.

Nota

swapcase() returns a new string; the original string remains unchanged.

Upgrade path

For more complex case transformations, use str.translate() with a custom translation table or regular expressions with re.sub() and a lambda.

Frequência: MediumFormulaicidade: Semi-fixedTipo de construção: method_callPrioridade de aquisição: Recognition firstPrioridade de output: BothTag de espaçamento: Short-termIdioma?: Sim

Log in to save chunks.