The String swapcase() method returns a new string that is the swap of the case of all the case-based characters present in the original string.
Syntax
my_string.swapcase()swapcase() Parameters
Python String swapcase() method does not take any parameters.
swapcase() Return Value
Python String swapcase() method returns a new string in which:
- All uppercase characters are converted to lowercase
- All lowercase characters converted to uppercase characters
- Other digits and symbols are left as they are.
Examples
Example 1: Swap case a String with swapcase()
The swapcase() method returns a new string with all uppercase characters converted to lowercase and all lowercase characters converted to uppercase characters.
my_str = 'Tutorial Reference'
result = my_str.swapcase()
print(result) # Output: tUTORIAL rEFERENCEoutput
tUTORIAL rEFERENCEExample 2: Swap case a String with Symbols with swapcase()
The swapcase() method ignores numbers and special characters in a string.
my_str = '1234 AbC $@%*'
result = my_str.swapcase()
print(result) # Output: 1234 aBc $@%*output
1234 aBc $@%*Example 3: Swap case with non-english characters
Not necessarily the swapcase of a swapcase of a string is equal to the original string.
For example, let's see that my_str.swapcase().swapcase() == my_str is not always true:
my_str1 = "Hello"
my_str2 = "groß"
print(my_str1.swapcase()) # Output: hELLO
print(my_str2.swapcase()) # Output: GROSS
print(my_str1.swapcase()) # Output: hELLO
print(my_str2.swapcase().swapcase()) # Output: gross
print(my_str1.swapcase().swapcase() == my_str1) # Output: True
print(my_str2.swapcase().swapcase() == my_str2) # Output: Falseoutput
hELLO
GROSS
hELLO
gross
True
False