ByteBoard Notes Notes

Input a string and check whether it is a palindrome; convert the case of its characters

Computer Science XI · Experiment 16 of 27 · Python

★ CBSE suggested11-CSPython programs
Expt. No.16
Page No.32

String palindrome and case swap

Aim

To write a Python program that checks whether a string is a palindrome and converts uppercase letters to lowercase and lowercase letters to uppercase.

Concepts used

Algorithm

  1. Input a string.
  2. Convert it to lowercase and compare it with its reverse (slice [::-1]).
  3. Display whether it is a palindrome.
  4. Build a new string: change each uppercase letter to lowercase and each lowercase letter to uppercase; keep other characters.
  5. Display the new string.

Program

# String palindrome check and case conversion text = input("Enter a string: ") word = text.lower()if word == word[::-1]:    print(text, "is a palindrome")else:    print(text, "is not a palindrome") swapped = ""for ch in text:    if ch.isupper():        swapped = swapped + ch.lower()    elif ch.islower():        swapped = swapped + ch.upper()    else:        swapped = swapped + chprint("After converting the case:", swapped)

A marked line continues the line above it. In your file, write it on the same line.

Output

Run 1
$ python string_palindrome_case_swap.py
Enter a string: Madam Madam is a palindrome After converting the case: mADAM
Run 2
$ python string_palindrome_case_swap.py
Enter a string: Python 3 Python 3 is not a palindrome After converting the case: pYTHON 3

✓ Printed by running this program, not typed by hand.

Result

"Madam" was a palindrome once both were in lowercase, and its case was swapped to "mADAM". "Python 3" was not a palindrome; it became "pYTHON 3", with the space and digit unchanged.

Viva voce: what the examiner may ask

01What does `word[

-1]` give? :: The string reversed: the slice takes every character with a step of -1.

02Why convert to lowercase before comparing?

"Madam" reversed is "madaM"; the comparison is case-sensitive, so it would fail without lower().

03Why build a new string instead of changing text?

Strings are immutable; their characters cannot be changed in place.

Variations for the lab test

  1. Ignore spaces too, so "Never odd or even" counts as a palindrome.
  2. Check the palindrome with a loop instead of slicing.
  3. Use the swapcase() method and compare the result.
! Common mistake Trying text[i] = ch.upper() raises TypeError, because a string is immutable.
Back to the 11-CS index