What is string.swapcase in Python?
The swapcase method converts the uppercase characters of a string to lowercase and vice-versa.
Syntax
str.swapcase()
Return value
swapcase returns a copy of the string with the cases swapped.
Example
Code
# convert all lowercase characters to upper case & uppercase characters to lower case and return a new stringstring = "all lower"print(string.swapcase());string = "UPPER"print(string.swapcase());string = "This IS a Mixed 10"print(string.swapcase());
In the code above, we call the swapcase method on different strings.
Important things to note
There is no guarantee that the following will apply.
string.swapcase().swapcase() === string
The criteria above may not be met for non-English characters. For example, let’s take the German word Straße, meaning road. The
German letter ß is equivalent to the English letter combination ss. So, when swapcase is called, Straße is converted to sTRASSE. When we call swapcase on sTRASSE, we will get Strasse and not Straße.
string = "Straße";print("The string is ", string)swapped_str = string.swapcase();print("The swapped string is ", swapped_str)print("\nCalling swapcase on already case swapped string")again_swapped_str = swapped_str.swapcase()print(again_swapped_str)print("\nChecking Straße.swapcase().swapcase()=== Straße")print(again_swapped_str == string)