How to Swap Case of Every Character in Python
Swap uppercase to lowercase and lowercase to uppercase for every character in a string using Python's built-in swapcase() method.
Python code
12 linesdef swap_case(text):
"""
Swap uppercase to lowercase and lowercase to uppercase
for every character in the given string.
"""
return text.swapcase()
if __name__ == "__main__":
sample = "Hello World! Python3.9"
result = swap_case(sample)
print(f"Input: {sample}")
print(f"Output: {result}")
Output
Input: Hello World! Python3.9
Output: hELLO wORLD! pYTHON3.9
How it works
The swapcase() method is a built-in string method that converts all uppercase characters to lowercase and all lowercase characters to uppercase, leaving non-alphabetic characters (like digits, punctuation, and spaces) unchanged. Because strings are immutable, swapcase() returns a new string rather than modifying the original. The function swap_case simply delegates to this method, making the code short and efficient. Running the sample input demonstrates how punctuation and digits remain untouched while letters are flipped.
Common mistakes
- Using `text.upper()` or `text.lower()` which only convert in one direction instead of swapping.
- Assuming `swapcase()` handles non-ASCII characters incorrectly; it handles Unicode but may not swap all alphabet systems as expected.
- Forgetting that `swapcase()` returns a new string; the original string remains unchanged.
Variations
- Use a list comprehension with `str.isupper()` and `str.lower()`/`str.upper()` for a manual swap.
- Use regular expressions with `re.sub` and a callback function to swap case for specific patterns.
Real-world use cases
- Normalizing user input in a text field to enforce consistent casing before storage or processing.
- Creating playful message transformations for chat bots or social media caption generators.
- Converting camelCase or PascalCase identifiers in code transformation tools for style consistency.
Sponsored
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.