Current Affairs updated daily
KalviGavaniKalviGavani
Class 12 · Tamil Nadu State Board

Samacheer Kalvi 12th Computer Science Chapter 8 Strings and String Manipulation Exercise Solutions | KalviGavani

Complete TN State Board Class 12 Computer Science Chapter 8 Strings and String Manipulation exercise solutions — string indexing, slicing, methods (upper, lower, find, replace, split, join, strip, count, isalpha, isdigit), formatting, escape characters, immutability with Python examples.

Updated 13 June 202611 min read

How to Use This Page

1. Attempt every exercise on your own before reading the solution. 2. Compare your approach with the solution — focus on the logic, not just the final answer. 3. Type and run the Python code on your computer; reading alone is not enough. 4. Review the Common Mistakes section to avoid errors that cost marks in exams.


Key Concepts

ConceptSyntax / ExampleDescription
String creations = "Hello"Strings use single, double, or triple quotes
Indexings[0] → 'H'Access a character by position (0-based)
Negative indexings[-1] → 'o'Count from the end (-1 is last)
Slicings[1:4] → 'ell'Extract substring: start inclusive, stop exclusive
Step slicings[::2] → 'Hlo'Every 2nd character
Reverses[::-1] → 'olleH'Reverses the string
ImmutabilityCannot do s[0]='h'Strings cannot be changed in place
Escape characters\n, \t, \\, \"Special characters inside strings
String formattingf-strings, .format(), %Insert values into strings

Important String Methods

MethodExampleResult
upper()"hi".upper()"HI"
lower()"HI".lower()"hi"
title()"hello world".title()"Hello World"
strip()" hi ".strip()"hi"
lstrip()" hi ".lstrip()"hi "
rstrip()" hi ".rstrip()" hi"
find()"hello".find("ll")2
rfind()"hello".rfind("l")3
index()"hello".index("ll")2
replace()"hi".replace("h", "H")"Hi"
split()"a b c".split()["a", "b", "c"]
join()"-".join(["a","b"])"a-b"
count()"banana".count("an")2
startswith()"hello".startswith("he")True
endswith()"hello".endswith("lo")True
isalpha()"abc".isalpha()True
isdigit()"123".isdigit()True
isalnum()"abc123".isalnum()True
isspace()" ".isspace()True
swapcase()"HeLLo".swapcase()"hEllO"
capitalize()"hello world".capitalize()"Hello world"
center()"hi".center(10, "-")"----hi----"
zfill()"5".zfill(3)"005"

Multiple Choice Questions (MCQs)

Q1. What is the output of "Hello"[1:4]?

  • (a) "Hel"
  • (b) "ell"
  • (c) "ello"
  • (d) "ell"
Answer(b) Slicing [1:4] gives characters at indices 1, 2, 3 which are 'e', 'l', 'l' → "ell". Note (b) and (d) are the same; the correct answer is "ell".

Q2. Which method converts "hello world" to "Hello World"?

  • (a) upper()
  • (b) capitalize()
  • (c) title()
  • (d) swapcase()
Answer(c) title() capitalizes the first letter of every word. capitalize() only capitalizes the first character.

Q3. What does "banana".count("an") return?

  • (a) 1
  • (b) 2
  • (c) 3
  • (d) 0
Answer(b) The substring "an" appears at positions 1 and 3, so count is 2.

Q4. Strings in Python are:

  • (a) Mutable
  • (b) Immutable
  • (c) Both mutable and immutable
  • (d) None of the above
Answer(b) Strings are immutable — they cannot be changed in place.

Q5. What is the result of "Python"[-3:]?

  • (a) "tho"
  • (b) "hon"
  • (c) "Pyt"
  • (d) Error
Answer(b) Negative index -3 refers to 'h'. [-3:] means from index -3 to the end → "hon".

Fill in the Blanks

Q1. The ______ method removes leading and trailing whitespace from a string.

Answerstrip()

Q2. ______ is the escape character for a new line.

Answer\n

Q3. "hello".find("x") returns ______.

Answer-1 (find returns -1 when the substring is not found)

Q4. The ______ method joins elements of a list into a single string using a separator.

Answerjoin()

Q5. "5".zfill(4) returns ______.

Answer"0005" (pads with zeros on the left to make the string 4 characters wide)

True or False

Q1. Strings in Python can be modified using indexing, e.g., s[0] = 'h'.

AnswerFalse — Strings are immutable; assigning to an index raises TypeError.

Q2. "Hello".lower() changes the original string.

AnswerFalse — It returns a new string; the original remains unchanged.

Q3. The split() method returns a list.

AnswerTrue — split() splits a string and returns a list of substrings.

Q4. Triple quotes can be used to create multi-line strings.

AnswerTrue — """...""" allows strings spanning multiple lines.

Q5. "123".isdigit() returns True.

AnswerTrue — All characters in "123" are digits.

Match the Following

Column AColumn B
1. `"abc".upper()(a) "ABC123" (True)
2. `"abc123".isalnum()(b) "AB"
3. `"a-b-c".split("-")(c) ["a", "b", "c"]
4. `"Hello"[1:3](d) "ABCD"
5. `"ab".join(["1","2","3"])(e) "1ab2ab3"
Answer1-b? Wait, let me re-do this properly.
Column AColumn B
1. "abc".upper()(a) "ABC"
2. "abc123".isalnum()(b) True
3. "a-b-c".split("-")(c) ["a", "b", "c"]
4. "Hello"[1:3](d) "el"
5. "ab".join(["1","2","3"])(e) "1ab2ab3"
Answer1-a, 2-b, 3-c, 4-d, 5-e

Short Answer Questions

Q1. Explain string immutability with an example.

Strings in Python cannot be modified after creation. Any operation that seems to modify a string actually creates a new string.

s = "Hello"
# s[0] = "h"  # TypeError: 'str' object does not support item assignment

# To "change" a string, create a new one:
s = "h" + s[1:]  # Create new string "hello"
print(s)  # hello

The original "Hello" object remains in memory until garbage-collected.

Q2. What is string slicing? Explain with examples.

Slicing extracts a substring using the syntax s[start:stop:step].

s = "Python"
print(s[0:3])    # Pyt  (indices 0,1,2)
print(s[2:])      # thon (from index 2 to end)
print(s[:4])      # Pyth (from start to index 3)
print(s[-3:])     # hon  (last 3 characters)
print(s[::2])     # Pto  (every 2nd character)
print(s[::-1])    # nohtyP (reversed)

Q3. Differentiate between find() and index().

Featurefind()index()
Returns position if foundYesYes
Returns if not found-1Raises ValueError
UsageSafe searchingWhen substring is guaranteed
s = "Hello World"
print(s.find("World"))   # 6
print(s.index("World"))  # 6
print(s.find("xyz"))     # -1
# s.index("xyz")         # ValueError: substring not found

Q4. Explain string formatting methods in Python.

Python offers three ways to format strings:

name = "Arun"
marks = 95

# 1. f-string (Python 3.6+, recommended)
print(f"{name} scored {marks}")  # Arun scored 95

# 2. format() method
print("{} scored {}".format(name, marks))  # Arun scored 95
print("{0} scored {1}".format(name, marks))  # Arun scored 95
print("{n} scored {m}".format(n=name, m=marks))  # Arun scored 95

# 3. %-formatting (older style)
print("%s scored %d" % (name, marks))  # Arun scored 95

Q5. List the escape characters in Python.

EscapeMeaning
\nNew line
\tHorizontal tab
\\Backslash
\'Single quote
\"Double quote
\rCarriage return
\bBackspace
print("Line1\nLine2")    # Prints on two lines
print("A\tB\tC")         # Prints with tabs
print("She said \"Hi\"") # Prints: She said "Hi"

Detailed Answers

Q1. Write a Python program to check whether a string is a palindrome.

def is_palindrome(s):
    """Check if a string is a palindrome."""
    s = s.lower().replace(" ", "")  # normalize
    return s == s[::-1]

# Method 1: Using slicing
word = input("Enter a string: ")
if is_palindrome(word):
    print(word, "is a palindrome")
else:
    print(word, "is not a palindrome")

# Method 2: Using loop (manual comparison)
def is_palindrome_loop(s):
    s = s.lower().replace(" ", "")
    left, right = 0, len(s) - 1
    while left < right:
        if s[left] != s[right]:
            return False
        left += 1
        right -= 1
    return True

Test: "madam" → True, "hello" → False, "racecar" → True

Q2. Write a program to count the number of vowels, consonants, digits, and special characters in a string.

def count_chars(s):
    """Count vowels, consonants, digits, and special characters."""
    vowels = "aeiouAEIOU"
    v = c = d = sp = 0
    for char in s:
        if char.isalpha():
            if char in vowels:
                v += 1
            else:
                c += 1
        elif char.isdigit():
            d += 1
        elif char != " ":
            sp += 1
    return v, c, d, sp

s = input("Enter a string: ")
v, c, d, sp = count_chars(s)
print(f"Vowels: {v}")
print(f"Consonants: {c}")
print(f"Digits: {d}")
print(f"Special characters: {sp}")

Q3. Write a program to reverse each word in a sentence while keeping word order.

sentence = input("Enter a sentence: ")
words = sentence.split()
reversed_words = [word[::-1] for word in words]
result = " ".join(reversed_words)
print("Original:", sentence)
print("Reversed words:", result)

# Input: Hello World Python
# Output: olleH dlroW nohtyP

Q4. Write a program to remove all duplicate characters from a string while preserving order.

def remove_duplicates(s):
    """Remove duplicate characters, preserving first occurrence order."""
    seen = set()
    result = ""
    for char in s:
        if char not in seen:
            seen.add(char)
            result += char
    return result

s = input("Enter a string: ")
print("After removing duplicates:", remove_duplicates(s))
# Input: "programming" → Output: "progamin"

Q5. Write a program to check if two strings are anagrams of each other.

def are_anagrams(s1, s2):
    """Check if two strings are anagrams."""
    s1 = s1.lower().replace(" ", "")
    s2 = s2.lower().replace(" ", "")
    return sorted(s1) == sorted(s2)

str1 = input("Enter first string: ")
str2 = input("Enter second string: ")

if are_anagrams(str1, str2):
    print("The strings are anagrams")
else:
    print("The strings are not anagrams")
# Input: "listen", "silent" → Anagrams
# Input: "hello", "world" → Not anagrams

Q6. Write a program to find the most frequent character in a string.

def most_frequent(s):
    """Find the most frequent character in a string."""
    freq = {}
    for char in s:
        if char != " ":
            freq[char] = freq.get(char, 0) + 1
    max_char = max(freq, key=freq.get)
    return max_char, freq[max_char]

s = input("Enter a string: ")
char, count = most_frequent(s)
print(f"Most frequent character: '{char}' appears {count} times")
# Input: "programming" → 'g' and 'r' and 'm' each appear twice
# The max() returns the first one encountered

Q7. Write a program to convert between different string cases.

s = "hello World PYTHON"

print("Original:       ", s)
print("upper():        ", s.upper())        # HELLO WORLD PYTHON
print("lower():        ", s.lower())        # hello world python
print("title():        ", s.title())        # Hello World Python
print("capitalize():   ", s.capitalize())   # Hello world python
print("swapcase():     ", s.swapcase())     # HELLO wORLD python

Common Mistakes

MistakeWhy It's WrongCorrection
s[0] = 'h'Strings are immutable — TypeErrorUse s = 'h' + s[1:] to create a new string
s.find() returns 0 when found at startConfusing 0 (found at index 0) with FalseRemember: find() returns the index or -1
Off-by-one in slicings[1:4] gives indices 1,2,3 (not 4)Stop index is exclusive
split() vs join() confusionsplit() breaks string → list; join() joins list → stringsep.join(list) and str.split(sep)
Forgetting replace() doesn't modify in places.replace('a','b') returns a new stringAssign: s = s.replace('a','b')
Using == to compare case-insensitively"Hello" == "hello" is FalseUse .lower() or .casefold() before comparing

Exam Checklist

  • [ ] I can use indexing and slicing on strings (positive and negative indices)
  • [ ] I can explain string immutability and work around it
  • [ ] I know all key string methods: upper, lower, find, replace, split, join, strip, count, isalpha, isdigit, isalnum
  • [ ] I can format strings using f-strings, .format(), and %-formatting
  • [ ] I understand escape characters (\n, \t, \\, \', \")
  • [ ] I can write programs for palindrome check, character counting, word reversal
  • [ ] I can differentiate find() vs index(), split() vs join()
  • [ ] I can trace string operations and predict outputs correctly

Frequently Asked Questions

Strings are immutable because once created, their characters cannot be changed in place. Any operation that appears to modify a string actually creates a new string object. For example, s[0] = 'H' raises a TypeError.
← Browse all Class 12 Exercise Solutions

Other question types — same chapter