W3Basic Logo

Python String swapcase() Method

The str.swapcase() method returns a copy of the string by converting all uppercase characters to lowercase and vice versa. If the string contains any special characters, symbols, or digits, the swapcase() method will ignore these characters.

Example:

text = "Python Tutorials"
print(text.swapcase())

Output

pYTHON tUTORIALS

Syntax

The Syntax of the str.swapcase() function is:

str.swapcase()

Here, str is a string.

Parameters

The str.swapcase() function takes no parameters.

Return Value

The str.swapcase() function returns a copy of a string by converting all the uppercase characters to lowercase and vice versa.

Example 1: How to use swapcase() method in Python

# Swap the case of a string with mixed case characters
text = "HeLLo WoRLD"
print(text.swapcase())  # Output: hEllO wOrld

# Swap the case of a string with all uppercase characters
text = "HELLO WORLD"
print(text.swapcase())  # Output: hello world

# Swap the case of a string with all lowercase characters
text = "hello world"
print(text.swapcase())  # Output: HELLO WORLD

# Swap the case of a string with special characters
text = "Hello World!@#"
print(text.swapcase())  # Output: hELLO wORLD!@#

Output

hEllO wOrld
hello world
HELLO WORLD
hELLO wORLD!@#

Example 2: swapcase() method in case of non-alphabetical characters.

In this example, the string "1234567890" consists only of digits, which are non-alphabetical characters. When we call swapcase() on this string, it does not affect the characters because they are not alphabetical. The output is the same as the original string.

# example string
str = "1234567890"

# swap the case of the characters in the string
swapped_string = str.swapcase()

print(swapped_string)  # Output: 1234567890

Output

1234567890

Example 3: swapcase() method on non-English characters

The swapcase() method in Python also works with non-English characters. It is case-sensitive, so it will only affect characters with upper and lowercase versions.

In this example, the string "Héllo Wörld!" contains the non-English characters "é" and "ör". The swapcase() method correctly swaps the case of these characters, resulting in a new string with the case reversed.

# example string with non-English characters
str = "Héllo Wörld!"

# swap the case of the characters in the string
swapped_string = str.swapcase()

print(swapped_string)  # Output: hÉLLO wÖRLD!

Output

hÉLLO wÖRLD!

Note: that not all non-English characters may not have both upper and lower case versions. In some languages, certain characters only have a single case. The swapcase() method will not affect those characters in these cases.

Reference: Python Official Docs

© 2023 W3Basic. All rights reserved.

Follow Us: