Input a string and check whether it is a palindrome; convert the case of its characters
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
- Input a string.
- Convert it to lowercase and compare it with its reverse (slice [::-1]).
- Display whether it is a palindrome.
- Build a new string: change each uppercase letter to lowercase and each lowercase letter to uppercase; keep other characters.
- 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
- Ignore spaces too, so "Never odd or even" counts as a palindrome.
- Check the palindrome with a loop instead of slicing.
- Use the
swapcase()method and compare the result.
! Common mistake Trying
text[i] = ch.upper() raises TypeError, because a string is immutable.