Python String swapcase()

The swapcase() method returns the string by converting all the characters to their opposite letter case( uppercase to lowercase and vice versa).

Example

name = "JoHn CeNa"

# converts lowercase to uppercase and vice versa print(name.swapcase())
# Output: jOhN cEnA

swapcase() Syntax

The syntax of the swapcase() method is:

string.swapcase()

swapcase() Parameters

The swapcase() method doesn't take any parameters.


swapcase() Return Value

The swapcase() method returns:

  • the string after converting its uppercase characters to lowercase, and lowercase characters to uppercase.

Example 1: Python swapcase()

sentence1 = "THIS SHOULD ALL BE LOWERCASE."

# converts uppercase to lowercase print(sentence1.swapcase())
sentence2 = "this should all be uppercase."
# converts lowercase to uppercase print(sentence2.swapcase())
sentence3 = "ThIs ShOuLd Be MiXeD cAsEd."
# converts lowercase to uppercase and vice versa print(sentence3.swapcase())

Output

this should all be lowercase.
THIS SHOULD ALL BE UPPERCASE.
tHiS sHoUlD bE mIxEd CaSeD. 

In the above example, we have used the swapcase() method to convert lowercase characters to uppercase and vice versa.

Here,

  • sentence1.swapcase() - converts every uppercase character in "THIS SHOULD ALL BE LOWERCASE." to lowercase
  • sentence2.swapcase() - converts every lowercase character in "this should all be uppercase." to uppercase
  • sentence3.swapcase() - converts the mixed string sentence3 i.e. "ThIs ShOuLd Be MiXeD cAsEd." to opposite letter case

Example 2: swapcase() with Non-English character

Not necessarily, string.swapcase().swapcase() == string. For example,

text = "groß "

# converts text to uppercase print(text.swapcase())
# performs swapcase() on text.swapcase() print(text.swapcase().swapcase())
print(text.swapcase().swapcase() == text)

Output

GROSS 
gross 
False

In the above example, we have used the swapcase() method with the German word 'groß'. The letter 'ß' is 'ss' in English.

Here,

  • text.swapcase() - converts 'groß' to uppercase i.e. 'GROSS'
  • text.swapcase().swapcase() - converts 'GROSS' to lowercase i.e. 'gross'

Hence the new string 'gross' is not equal to text.

Note: If you want to convert a string to lowercase only, use lower(). Likewise, if you want to convert string to uppercase only, use upper().


Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges