Editor

Python Program to Toggle the Case of a String

Beginner · Strings

Toggling the case of a string means turning every capital letter into a small one and every small letter into a capital, so "Hello World" becomes "hELLO wORLD". Characters that are not letters, like digits and spaces, stay the same.

Program

toggle_case.py
text = "Hello World 2026" # or: text = input("Enter a string: ")
result = ""
for ch in text:
if ch.isupper():
result += ch.lower()
elif ch.islower():
result += ch.upper()
else:
result += ch # digits, spaces and symbols stay the same
print("Original:", text)
print("Toggled: ", result)
Output
Original: Hello World 2026
Toggled:  hELLO wORLD 2026

How it works

  1. ch.isupper() is True for a capital letter, which ch.lower() turns into a small one.
  2. ch.islower() is True for a small letter, which ch.upper() turns into a capital.
  3. Anything else, such as a digit, space or punctuation mark, is neither, so it is copied unchanged.
  4. The new characters are added to result one by one, because the original string cannot be changed in place.

Other ways to write it

Using swapcase()

Using swapcase()
text = "Hello World 2026"
print("Toggled:", text.swapcase())
print("PyThOn ->", "PyThOn".swapcase())
Output
Toggled: hELLO wORLD 2026
PyThOn -> pYtHoN

swapcase() is the built-in way to toggle case and gives the same result as the loop.

Using character codes

Using character codes
text = "Hello World 2026"
result = ""
for ch in text:
code = ord(ch)
if 65 <= code <= 90: # A to Z
result += chr(code + 32)
elif 97 <= code <= 122: # a to z
result += chr(code - 32)
else:
result += ch
print("Toggled:", result)
Output
Toggled: hELLO wORLD 2026

Each small letter has a code 32 more than its capital (ord("a") is 97 and ord("A") is 65), so adding or taking away 32 switches the case. This works for English letters only.

Try it yourself

Count how many letters changed from capital to small, and how many from small to capital.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises