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.
print("Hello World".swapcase()) # hELLO wORLD
Try it
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.
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
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(), notswapcase(). - Related conversions:
upper(),lower(),title()andcapitalize(). - Strings are immutable, so the original is unchanged.
- Also on
bytesandbytearray, where only ASCII letters change.