Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to invert case for all letters in a string in Python?
A string is a sequence of characters that can represent words, sentences, or any text data. In Python, you can manipulate string cases using various built-in methods.
In this article, we will explore how to invert the case for all letters in a string in Python using different approaches.
Using the swapcase() Method
The most efficient way to invert case is using the built-in swapcase() method. This method converts all lowercase letters to uppercase and all uppercase letters to lowercase ?
Syntax
string.swapcase()
Example
Here's how to use swapcase() to invert the case of a string ?
text = "Welcome to Tutorialspoint"
print("Original string:")
print(text)
print("Inverted case string:")
print(text.swapcase())
Original string: Welcome to Tutorialspoint Inverted case string: wELCOME TO tUTORIALSPOINT
Using Manual Loop Approach
You can also invert case manually by iterating through each character and using isupper(), upper(), and lower() methods ?
Example
This approach gives you more control over the inversion process ?
text = "Welcome to Tutorialspoint"
print("Original string:")
print(text)
inverted_text = ""
for char in text:
if char.isupper():
inverted_text += char.lower()
elif char.islower():
inverted_text += char.upper()
else:
inverted_text += char # Keep non-alphabetic characters as-is
print("Inverted case string:")
print(inverted_text)
Original string: Welcome to Tutorialspoint Inverted case string: wELCOME TO tUTORIALSPOINT
Using List Comprehension
A more Pythonic approach using list comprehension for case inversion ?
text = "Welcome to Tutorialspoint"
inverted_text = ''.join([char.lower() if char.isupper() else char.upper() for char in text])
print("Original string:", text)
print("Inverted case string:", inverted_text)
Original string: Welcome to Tutorialspoint Inverted case string: wELCOME TO tUTORIALSPOINT
Comparison of Methods
| Method | Performance | Readability | Best For |
|---|---|---|---|
swapcase() |
Fastest | Excellent | Simple case inversion |
| Manual Loop | Slower | Good | Custom logic needed |
| List Comprehension | Moderate | Good | Pythonic one-liner |
Conclusion
The swapcase() method is the most efficient and readable way to invert case in Python strings. Use manual approaches when you need custom logic or want to understand the underlying process.
