Interview Question Series | Season 2

Lesson: Alternate Case of a Character in Python

Objective:

Learn how to alternate the case of a character in Python using two approaches: the old manual solution and the new bitwise solution.


Initial Code:

Here’s the starting code:

char = 'F'

for i in range(4):
    print(char)
    # Add one line here

The goal is to alternate the case of the character 'F' on each iteration, producing the following output:

F
f
F
f

Old Solution (Using ASCII Comparison)

The old solution manually checks the ASCII range of the character to toggle its case:

char = 'F'

for i in range(4):
    print(char)
    if 'A' <= char <= 'Z':  # Check if the character is uppercase
        char = chr(ord(char) + 32)  # Convert to lowercase by adding 32
    else:
        char = chr(ord(char) - 32)  # Convert to uppercase by subtracting 32

How It Works:

  1. Check the Character Range:
    • 'A' <= char <= 'Z': Checks if the character is uppercase (ASCII range 65–90).
    • Else: Assumes the character is lowercase (ASCII range 97–122).
  2. Toggle Case Using ASCII Arithmetic:
    • Uppercase → Lowercase:
      • Add 32 to the ASCII value (ord(char) + 32).
    • Lowercase → Uppercase:
      • Subtract 32 from the ASCII value (ord(char) - 32).
  3. Convert Back to a Character:
    • chr() converts the updated ASCII value back to a character.

New Solution (Using Bitwise XOR)

The more efficient solution toggles the case using a bitwise operation:

char = 'F'

for i in range(4):
    print(char)
    char = chr(ord(char) ^ (1 << 5))

How It Works:

  1. Convert the Character to ASCII:
    • ord(char) gets the ASCII value of the character.
  2. Toggle the 5th Bit:
    • (1 << 5) creates a value of 32 (binary 00100000).
    • XOR (^) toggles the 5th bit of the ASCII value:
      • Uppercase → Lowercase
      • Lowercase → Uppercase
  3. Convert Back to a Character:
    • chr() converts the modified ASCII value back to a character.

Output (Both Solutions):

F
f
F
f

Comparison of the Two Solutions:

Approach Code Length Efficiency Ease of Understanding
Old Solution (ASCII) Longer Moderate Easier for Beginners
New Solution (Bitwise) Shorter More Efficient Requires Knowledge of Bits

Key Takeaways:

  1. The old approach uses basic arithmetic and range checks, making it beginner-friendly.
  2. The new bitwise approach is compact and efficient, ideal for optimizing performance.
  3. Both solutions produce the same result but differ in style and complexity.
Scroll to Top