Python String swapcase() Function
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.
note
- The lowercase characters in the string will be converted into uppercase characters.
- The uppercase characters in the string will be converted into lowercase characters.
- Other digits and symbols are left as they are.
note
Syntax
my_string.swapcase()
swapcase() Parameters
Python String swapcase()
function does not take any parameters.
swapcase() Return Value
Python String swapcase()
function 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 rEFERENCE
output
tUTORIAL rEFERENCE
Example 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ß"
# converts text to uppercase
print(my_str1.swapcase()) # Output: hELLO
print(my_str2.swapcase()) # Output: GROSS
# performs swapcase of thw swapcase of the string
print(my_str1.swapcase()) # Output: hELLO
print(my_str2.swapcase().swapcase()) # Output: gross
# check if swapcase of swapcase of the string is equal to original string
print(my_str1.swapcase().swapcase() == my_str1) # Output: True
print(my_str2.swapcase().swapcase() == my_str2) # Output: False
output
hELLO
GROSS
hELLO
gross
True
False