Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

What is string.swapcase in Python?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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 string
string = "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)

RELATED TAGS

python
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring