Skip to content
Tutorials Center
My learning

Topics

Python Reference Β· String Methods

Python str.swapcase() method

Reference for Python str.swapcase(): swap upper-case letters to lower case and the reverse, how non-letters and special Unicode characters behave.

The str.swapcase() method returns a copy of the string in which every upper-case letter becomes lower case and every lower-case letter becomes upper case. Characters that have no case, such as digits, spaces and punctuation, are left alone.

It is rarely needed in real programs, but it is useful for small text puzzles, toggling the case of a typed word and demonstrating how case mapping works.

Python
print("Hello World".swapcase())   # hELLO wORLD

Try it

Python Swapping case

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Unicode surprises

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
str.swapcase()

The method takes no arguments.

Return value: a new string.

Usage notes

  • Not always reversible. For most text, s.swapcase().swapcase() == s, but some Unicode characters change length: "ß".swapcase() is "SS", and swapping again gives "ss", not "ß".
  • Non-letters are unchanged, and uncased letters from scripts without case are returned as they are.
  • Title-case letters such as Η… (a single character) are returned unchanged.
  • Not a comparison tool. For caseless comparison use casefold(), not swapcase().
  • Related conversions: upper(), lower(), title() and capitalize().
  • Strings are immutable, so the original is unchanged.
  • Also on bytes and bytearray, where only ASCII letters change.