swapcase() flips the case of every letter: capitals become small letters and small letters become capitals. "Hello World" becomes "hELLO wORLD". Characters without case are copied unchanged.
Like all string methods it returns a new string. It is rarely needed, but it is a neat fix for text that was typed with Caps Lock on by mistake, and a good way to see how case works.
text.swapcase() is a method of the built-in str type: call it on a string with dot notation. No import is needed, and it never changes the original string.
Syntax
Call it on any string. There are no arguments, but the parentheses are required.
python
result = text.swapcase()
Call
What it does
"Hello World".swapcase()
Returns 'hELLO wORLD'.
"PYTHON 3".swapcase()
Returns 'python 3'. The digit has no case and is kept.
"Python".swapcase().swapcase() == "Python"
Returns True. Swapping twice gives the original back for plain English letters.
Every letter flips.H becomes h, and the lower case ello becomes ELLO.
Flip again. Calling swapcase() on the flipped text brings back "Hello World".
No edit in place.greeting was never changed, so the last line prints the original.
Example 2 — Repair Text Typed With Caps Lock On
Text typed with Caps Lock on has its case reversed, which swapcase() repairs in one call.
python
typed = "hELLO, mY nAME IS rIA."
fixed = typed.swapcase()
print(typed)
print(fixed)
Output
hELLO, mY nAME IS rIA.
Hello, My Name is Ria.
How It Works
The mistake. Every letter was typed in the opposite case, so the sentence looks odd.
One call repairs it.swapcase() flips every letter back to what the writer meant.
Only for fully reversed text.swapcase() flips every letter, including ones that were typed correctly, so use it only when the whole text was typed with Caps Lock on.
Example 3 — Count Capitals Before and After
Count the capital letters of a string and of its flipped copy.
python
text = "Python 3.12 Rocks"
flipped = text.swapcase()
print(flipped)
print(sum(1 for ch in text if ch.isupper()))
print(sum(1 for ch in flipped if ch.isupper()))
Output
pYTHON 3.12 rOCKS
2
9
How It Works
Flip first. The digits and the dot stay, while P and R become lower case and the other letters become capitals.
Two capitals at the start. The original has only P and R in upper case, so the first count is 2.
Nine after the flip. The nine letters that were lower case are now capitals, so the second count is 9.
Frequently Asked Questions
It returns a new string in which every upper case letter is lower case and every lower case letter is upper case. Other characters are unchanged.
No. Strings are immutable, so swapcase() returns a new string. Assign the result if you want to keep it.
For plain English letters, yes. For a few international characters, such as the German sharp s, it may not.
Mostly for repairing text typed with Caps Lock on, or for small puzzles. Everyday code uses lower() and upper() much more often.
They have no case, so swapcase() copies them to the new string unchanged.