Python string swapcase() Method
Last Updated :
02 Jan, 2025
Improve
swapcase()
method in Python is used to return a new string where all the uppercase characters in the original string are converted to lowercase, and all the lowercase characters are converted to uppercase.
Let's us understand this with the help of an example:
s = "I love Python"
swapped_text = s.swapcase()
print(swapped_text)
Output
i LOVE pYTHON
Explanation:
- The uppercase characters are converted to lowercase.
- The lowercase characters are converted to uppercase.
- The result is a toggle-case version of the original string.
Table of Content
Syntax of String swapcase() method
string.swapcase()
Parameters
- The
swapcase()
method does not take any parameters.
Return Type
- Returns a new string where all uppercase characters are converted to lowercase and all lowercase characters are converted to uppercase.
Simple toggle case
Let’s see how sswapcase()
works with a mixed-case string:
s = "Python IS Awesome!"
res = s.swapcase()
print(res)
Output
pYTHON is aWESOME!
Explanation:
- Uppercase characters
P
,I
,S
, andA
are converted to lowercase. - Lowercase characters
y
,t
,h
,o
,n
, andw
are converted to uppercase. - The method returns a toggle-case version of the input string.
Handling numeric and special characters
The swapcase()method does not affect numeric or special characters:
s = "123 Python!"
res = s.swapcase()
print(res)
Output
123 pYTHON!
Explanation:
- The numbers
123
and the special character!
remain unchanged. - Only alphabetic characters are toggled.
Applying swapcase()
to an all-uppercase string
What happens if the string contains only uppercase characters?
s = "HELLO"
res = s.swapcase()
print(res)
Output
hello
Explanation:
- All uppercase characters are converted to lowercase.
- The method works seamlessly with strings of any case.
4. Applying swapcase()
to an all-lowercase string
Similarly, let’s see the result with an all-lowercase string:
s = "world"
res = s.swapcase()
print(res)
Output
WORLD
Explanation:
- All lowercase characters are converted to uppercase.
- The method ensures a complete toggle of the string’s case.