How to invert case for all letters in a string in Python?


A string is a group of characters that can represent a single word or a complete sentence. In Python there is no need to declare variables explicitly using the datatype specifier you can directly assign them to a literal. Therefore, compared to other technologies like Java it is easy to use Python strings.

For manipulating and accessing strings, Python includes several built in functions and methods. You can find these functions in a class named String.

In this article, we are going to focus on how to invert the case for all letters in a string in Python.

Using the swapcase() function

One way to achieve this is using the inbuilt string library function swapcase(). This function takes a string as input and returns the updated string as output. It swaps all the lower case to upper case and all the upper case to lower case.

Example

In the example given below, we are taking a string as input and we are inversing the case of that string using the swapcase() method.

str1 = "Welcome to Tutorialspoint" print("The original string is ") print(str1) print("The updated string is ") print(str1.swapcase())

Output

The output of the above given example is,

The original string is
Welcome to Tutorialspoint
The updated string is
wELCOME TO tUTORIALSPOINT

Using the loops and conditionals (brute force)

You can invert case for all letters in a string using the brute force approach where we traverse through the entire string and check if it is a lower case or upper case and invert it using the upper() and the lower() method. This is a time consuming and complex approach.

Example

In the program given below, we are taking a string as input, and using the lower() and upper() methods we inverted the cases of the string and printed it as output.

str1 = "Welcome to Tutorialspoint" print("The original string is ") print(str1) newstr = "" print("The updated string is ") for i in str1: if i.isupper(): newstr += i.lower() else: newstr += i.upper() print(newstr)

Output

The output of the above example is,

The original string is
Welcome to Tutorialspoint
The updated string is
wELCOME TO tUTORIALSPOINT

Updated on: 19-Oct-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements