Python bytes.swapcase usage detailed explanation and examples

Python bytes.swapcase Usage Detailed Explanation and Examples

bytes.swapcase() is a Python method that swaps the case of a byte string.

The syntax of this method is as follows:

bytes.swapcase()

Where bytes is a bytes object, which can be a bytes variable or directly embedded in a bytes string.

Here are three examples:

Example 1:

s = b'Hello, Python"
result = s.swapcase()
print(result) # Output: b'hELLO, pYTHON'

Explanation: Converts the uppercase letters in the byte string b"Hello, Python" to lowercase letters, and vice versa, resulting in the result b'hELLO, pYTHON'.

Example 2:

s = b"1234abcd"
result = s.swapcase()
print(result) # Output: b'1234ABCD'

Explanation: Converts the lowercase letters in the byte string b"1234abcd" to uppercase letters, and vice versa, resulting in the result b'1234ABCD'.

Example 3:

s = b"@#<span class="katex math inline">%^"
result = s.swapcase()
print(result) # Output: b'@#</span>%^'

Explanation: Swaps the case of the characters in the byte string b"@#$%^". However, since the byte string contains only non-alphabetic characters, the result remains unchanged after swapping the case, i.e., b'@#$%^'.

Note: The bytes.swapcase() method is a Python 3 method. If you are using Python 2, use the str.swapcase() method to achieve the same functionality.

Leave a Reply

Your email address will not be published. Required fields are marked *