Python String swapcase()

Filed Under: Python

Python String swapcase() function returns a new string with uppercase characters converted to lowercase and vice versa.

Python String swapcase()

This function doesn’t accept any parameter. Note that it’s not necessarily True that s.swapcase().swapcase() == s.

Let’s look at some examples of swapcase() function.


s = 'hello'

print(s.swapcase())

s = 'HellO'
print(s.swapcase())

Output:


HELLO
hELLo

Python String swapcase()

Let’s look at an example with special Unicode characters.


s = 'çå†'
print(s.swapcase())
print(s.swapcase().swapcase())
print(s.swapcase().swapcase() == s)

Output:


Çņ
çå†
True

python string swapcase() with special characters

Note that not every character has Lowercase and Uppercase version. For example, ‘†’ character doesn’t have Uppercase or Lowercase version.

Finally, let’s look at an example where s.swapcase().swapcase() == s returns False.


s = 'ß'  # German lowercase letter 'ß' is equivalent to "ss"
print(s.swapcase())
print(s.swapcase().swapcase())
print(s.swapcase().swapcase() == s)

Output:


SS
ss
False

Python string swapcase() ß example

You can checkout more Python examples from our GitHub Repository.

Official Documentation: swapcase()

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages