String method

str.swapcase()

Returns a copy of a string where capital letters become small and small letters become capitals. Other characters stay.

BeginnerEvery example below runs in your browser. Change the code and press Run.

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

Pythoneditable
print("Hello World".swapcase())
print("pYTHON 3".swapcase())
Output
hELLO wORLD
Python 3

2Fix text typed with Caps Lock on

Pythoneditable
typed = "hELLO, mY NAME IS aNA"
print(typed.swapcase())
Output
Hello, My name is Ana

3Swapping twice is not always a round trip

Pythoneditable
word = "Straße"
once = word.swapcase()
twice = once.swapcase()
print(once)
print(twice)
print(twice == word)
Output
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.

Pythoneditable
text = "MiXeD"
print(text.swapcase())
print(text.lower())
Output
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.

Spotted a mistake on this page? Tell us