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.

Easy Python 3.9+ Aug 9, 2026 Strings & text 13 views 0 copies

Python code

12 lines
Python 3.9+
def 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

stdout
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

  1. Use a list comprehension with `str.isupper()` and `str.lower()`/`str.upper()` for a manual swap.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.