bytes.swapcase() returns a new bytes object in which every ASCII lowercase letter is turned into uppercase and every ASCII uppercase letter into lowercase. All other bytes are copied unchanged.
In ASCII, an uppercase letter and its lowercase partner differ by exactly 32, so swapping case is the same as flipping one bit of each letter byte. For ASCII data, calling swapcase() twice always gives back the original.
bytes.swapcase() is a method of the built-in bytes type: call it on a bytes object with dot notation, such as data.swapcase(...). No import is needed, and bytearray objects have the same method.
Syntax
No arguments; the swapped copy is returned.
python
result = data.swapcase()
Call
What it does
b"Hello".swapcase()
Returns b'hELLO'.
b"a1B2".swapcase()
Returns b'A1b2'.
bytearray(b"Ok").swapcase()
Returns bytearray(b'oK').
The round-trip guarantee holds for bytes because only ASCII letters change; the str version can break it for some Unicode letters.
Method signatures
python
bytes.swapcase()
# returns a new bytes object (bytearray.swapcase() returns a bytearray)
Parameters
swapcase() takes no parameters.
Return Value
Return Value
Description
bytes
A copy with the case of each ASCII letter inverted.
Python Examples
Example 1 — Swap Case in ASCII and UTF-8 Bytes
Swap a greeting, a mixed token, and the UTF-8 bytes of a French word that contains accented letters.
python
print(b"Hello World 42".swapcase())
print(b"aBc-XyZ".swapcase())
print(b"\xc3\x89t\xc3\xa9".swapcase())
Output
b'hELLO wORLD 42'
b'AbC-xYz'
b'\xc3\x89T\xc3\xa9'
How It Works
Every letter flips. H becomes h and the lowercase letters become capitals; the space and digits stay.
Symbols in between. The hyphen is left alone while letters on both sides swap.
Only the t changes. The word starts and ends with two-byte accented letters, which are not ASCII, so only the middle t becomes T.
Example 2 — Swapping Twice Restores ASCII Data
Swap a token, swap it back, and check the case tests on the intermediate value.