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
Original: Hello World 2026 Toggled: hELLO wORLD 2026
How it works
ch.isupper()isTruefor a capital letter, whichch.lower()turns into a small one.ch.islower()isTruefor a small letter, whichch.upper()turns into a capital.- Anything else, such as a digit, space or punctuation mark, is neither, so it is copied unchanged.
- The new characters are added to
resultone by one, because the original string cannot be changed in place.
Other ways to write it
Using swapcase()
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
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.
Related programs
- Capitalize the First Letter of Each Word
- Count Vowels, Consonants, Uppercase and Lowercase Letters
- Find the ASCII Value of a Character
- Check a Palindrome String
- Reverse a String
- Generate a Random Password
- Count the Frequency of Each Character in a String
- Count the Words in a String
- Remove Punctuation from a String
All Python programs · CBSE class 12 practical file · Python exercises