0
0
PythonHow-ToBeginner · 3 min read

How to Swap Case of String in Python: Simple Guide

In Python, you can swap the case of all letters in a string using the swapcase() method. This method converts uppercase letters to lowercase and lowercase letters to uppercase in the string.
📐

Syntax

The swapcase() method is called on a string object and returns a new string with swapped letter cases.

  • string.swapcase(): Returns a new string with uppercase letters changed to lowercase and vice versa.
python
swapped_string = your_string.swapcase()
💻

Example

This example shows how to use swapcase() to change uppercase letters to lowercase and lowercase letters to uppercase in a string.

python
text = "Hello World!"
swapped = text.swapcase()
print(swapped)
Output
hELLO wORLD!
⚠️

Common Pitfalls

One common mistake is trying to swap case without calling the method on a string instance or forgetting the parentheses, which leads to errors or unexpected results.

Also, swapcase() does not change non-letter characters like numbers or symbols.

python
text = "Python3"
# Wrong: forgetting parentheses
# swapped = text.swapcase  # This is a method, so it needs () to execute

# Correct:
swapped = text.swapcase()
print(swapped)  # Output: pYTHON3
Output
pYTHON3
📊

Quick Reference

MethodDescription
swapcase()Returns a new string with uppercase letters converted to lowercase and vice versa
Example: "Hello".swapcase()Returns "hELLO"
Non-letter charactersRemain unchanged when using swapcase()

Key Takeaways

Use the string method swapcase() to swap uppercase and lowercase letters in Python.
swapcase() returns a new string and does not modify the original string.
Non-letter characters like digits and symbols are not affected by swapcase().
Always include parentheses when calling swapcase() to execute the method.
swapcase() is a simple and effective way to invert letter cases in strings.