Python String swapcase() Method



The Python string swapcase() method is used to swap the case of all the case-based characters present in a string. That is, the lowercase characters in the string will be converted into uppercase characters and vice-versa.

The lowercase characters are characters that are not capitalized letters; whereas, the uppercase characters are capitalized characters.

Note βˆ’ This method does not raise an error when encountered with the digit and symbol characters in a string but returns them as it is.

Syntax

Following is the syntax for Python String swapcase() method βˆ’

str.swapcase()

Parameters

This method does not accept parameters.

Return Value

This method returns a copy of the string in which all the case-based characters have had their case swapped.

Example

When we call this method on an input string with all lowercase letters, it results in a string containing uppercase letters.

The following example shows the usage of Python String swapcase() method. In this example, we create a string with all lowercase characters in it, say "this is string example....wow!!!". The swapcase() method is called on this string and the return value will be the uppercased string.

str = "this is string example....wow!!!";
print(str.swapcase())

When we run above program, it produces following result βˆ’

THIS IS STRING EXAMPLE....WOW!!!

Example

When we call this method on an input string with all uppercase letters, it results in a string containing lowercase letters.

In the given example, we create a string with all uppercase characters in it, say "THIS IS STRING EXAMPLE....WOW!!!". The swapcase() method is called on this string and the return value will be the lowercased string.

str = "THIS IS STRING EXAMPLE....WOW!!!";
print(str.swapcase())

When we compile and run the given program, the output is produced as follows βˆ’

this is string example....wow!!!

Example

When we call this method on an input string, it returns a string with the cases of its case-based characters swapped.

The following program creates a string, "TuToRiAlSpOiNt", containing both lowercase and uppercase letters as input. The swapcase() method is invoked on this string to obtain the final string with its cases swapped.

str = "TuToRiAlSpOiNt";
print(str.swapcase())

The output for the above program is produced as given below βˆ’

tUtOrIaLsPoInT

Example

When the string passed contains non-alphabetical characters, the method will return the original string.

Let us look at the usage of the swapcase() method on non-casebased values as follows βˆ’

str = "121$%^";
print(str.swapcase())

If we compile and run the above program, the output is displayed as follows βˆ’

121$%^
python_strings.htm
Advertisements