Python string swapcase() Method (original) (raw)
Last Updated : 02 Jan, 2025
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:
Python `
s = "I love Python"
swapped_text = s.swapcase() print(swapped_text)
`
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
- Examples of swapcase() method
- Frequently Asked Questions (FAQs) on swapcase() Method
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:
Python `
s = "Python IS Awesome!"
res = s.swapcase() print(res)
`
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:
Python `
s = "123 Python!"
res = s.swapcase() print(res)
`
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?
Python `
s = "HELLO" res = s.swapcase() print(res)
`
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:
Python `
s = "world" res = s.swapcase() print(res)
`
Explanation:
- All lowercase characters are converted to uppercase.
- The method ensures a complete toggle of the string’s case.