Part of the series

Several example codes

~2 min read • Updated Oct 11, 2025

Program Overview

This Python program receives a string and toggles the case of each letter using the XOR bitwise operator.
If a character is lowercase, it becomes uppercase; if it’s uppercase, it becomes lowercase.
This works by XOR-ing the ASCII value of the character with 0x20 (decimal 32), which flips the sixth bit responsible for case.


Python Code:


def toggle_case_xor(text: str) -> str:
    result = ""
    for ch in text:
        if 'a' <= ch <= 'z' or 'A' <= ch <= 'Z':
            toggled = chr(ord(ch) ^ 0x20)
            result += toggled
        else:
            result += ch
    return result

# Run the program
input_text = input("Enter your text: ")
output_text = toggle_case_xor(input_text)
print(f"Toggled text: {output_text}")

Sample Output (input: "Hello World"):


Toggled text: hELLO wORLD

Step-by-Step Explanation:

- The user enters a string
- The program loops through each character
- If the character is a letter, it applies XOR with 0x20 to flip its case
- Non-letter characters remain unchanged
- The final toggled string is printed


Written & researched by Dr. Shahin Siami