str.swapcase()
Returns a copy of a string where capital letters become small and small letters become capitals. Other characters stay.
str.swapcase()swapcase() flips the case of every letter: "Hello" becomes "hELLO". Digits, spaces and symbols are left alone.
It is not used often in real programs. Its classic job is fixing text typed with Caps Lock left on by mistake.
Swapping twice does not always give the original back: "ß" becomes "SS", and swapping again gives "ss".
Return value
A new string with the case of every letter flipped.
Examples
1Flip the case
print("Hello World".swapcase())
print("pYTHON 3".swapcase())hELLO wORLD Python 3
2Fix text typed with Caps Lock on
typed = "hELLO, mY NAME IS aNA"
print(typed.swapcase())Hello, My name is Ana
3Swapping twice is not always a round trip
word = "Straße"
once = word.swapcase()
twice = once.swapcase()
print(once)
print(twice)
print(twice == word)sTRASSE Strasse False
Common mistakes
Using swapcase() to make text upper or lower case
swapcase() depends on the current case of each letter, so the result is mixed when the input is mixed. Use upper() or lower() when you want one case.
text = "MiXeD"
print(text.swapcase())
print(text.lower())mIxEd mixed
Questions people ask
How do I detect Caps Lock text?
A rough test: the text has letters and most of them are capitals, sum(c.isupper() for c in t) > sum(c.islower() for c in t).
Does swapcase() work with accented letters?
Yes: "Élan".swapcase() gives "éLAN".
Is s.swapcase().swapcase() always s?
No. Letters like ß change into two letters on the way, as the example shows.