Current Affairs updated daily
KalviGavaniKalviGavani

Strings & String Manipulations Solutions | KalviGavani

TN Class 11 CS Strings and String Manipulations exercise solutions — string operations, slicing, methods, formatting with Python code examples.

Updated 15 June 202617 min read

Exercise Solutions Available

Step-by-step answers for all textbook questions in this chapter

View Solutions →

Strings and String Manipulations — TN Class 11 CS Exercise Solutions

Complete exercise solutions for the Tamil Nadu Board Class 11 Computer Science chapter Strings and String Manipulations. Covers string creation, indexing, slicing, operations, methods, and formatting with working Python code.


How to Use This Page

1. Attempt each exercise on your own first — write Python code before checking solutions. 2. Run every example in IDLE or a Python editor to verify the output. 3. Practise slicing — draw the index positions on paper before solving slicing questions. 4. Understand immutability — remember that strings cannot be changed in place; methods return new strings. 5. Memorise string methods — many MCQ and fill-in-the-blank questions test method names and return types.


Key Concepts (Quick Recap)

ConceptSyntax/ExampleDetails
String creations = "Hello"Sequence of characters in quotes
Single chars = 'A'A string of length 1
Triple quotess = """Line 1\nLine 2"""Multi-line strings
Indexings[0], s[-1]Access individual characters
Slicings[start:end:step]Extract substring (end is exclusive)
Concatenations1 + s2Join two strings
Repetitions * 3Repeat string n times
Membership'el' in 'Hello'Check if substring exists → True
Lengthlen(s)Number of characters
ImmutabilityStrings cannot be changedMethods return NEW strings

String Indexing Diagram for s = "PYTHON":

Index: 0 1 2 3 4 5 Char: P Y T H O N Index: -6 -5 -4 -3 -2 -1
ExpressionResultExplanation
s[0]'P'First character
s[5]'N'Last character (positive index)
s[-1]'N'Last character (negative index)
s[-6]'P'First character (negative index)
s[1:4]'YTH'From index 1 up to (not including) 4
s[:3]'PYT'From beginning up to index 3
s[3:]'HON'From index 3 to end
s[::-1]'NOHTYP'Reverse the string
s[0:6:2]'PTO'Every 2nd character

Common String Methods:

MethodExampleResultDescription
upper()"hi".upper()"HI"Convert to uppercase
lower()"HI".lower()"hi"Convert to lowercase
title()"hello world".title()"Hello World"First letter of each word uppercase
capitalize()"hello".capitalize()"Hello"First letter uppercase
strip()" hi ".strip()"hi"Remove leading/trailing spaces
lstrip()" hi ".lstrip()"hi "Remove leading spaces
rstrip()" hi ".rstrip()" hi"Remove trailing spaces
find()"hello".find("ll")2Index of first occurrence, -1 if not found
count()"banana".count("a")3Count occurrences
replace()"hi".replace("h", "H")"Hi"Replace substring
split()"a,b,c".split(",")["a","b","c"]Split into list
join()",".join(["a","b","c"])"a,b,c"Join list into string
startswith()"hello".startswith("he")TrueCheck if string starts with prefix
endswith()"hello".endswith("lo")TrueCheck if string ends with suffix
isalpha()"abc".isalpha()TrueCheck if all characters are alphabetic
isdigit()"123".isdigit()TrueCheck if all characters are digits
isalnum()"abc123".isalnum()TrueCheck if all characters are alphanumeric
swapcase()"HeLLo".swapcase()"hEllO"Swap case of each character
center()"hi".center(10)" hi "Center string in given width
zfill()"5".zfill(3)"005"Pad with zeros on the left

I. Choose the Best Answer (MCQs)

Q1. Strings in Python are: (a) Mutable (b) Immutable (c) Both (d) None of these

Answer(b) Immutable

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


Q2. What is the output of "Hello"[1:4]? (a) "Hell" (b) "ello" (c) "ell" (d) "Hel"

Answer(c) "ell"

Slicing [1:4] starts at index 1 ('e') and goes up to (but not including) index 4 ('o'). Result: "ell".


Q3. Which method converts a string to uppercase? (a) upper() (b) uppercase() (c) toupper() (d) toUpper()

Answer(a) upper()

The upper() method returns a new string with all characters converted to uppercase. "hello".upper() gives "HELLO".


Q4. What does "Python".find("th") return? (a) 2 (b) 0 (c) -1 (d) Error

Answer(a) 2

find() returns the index of the first occurrence of the substring. In "Python", "th" starts at index 2 (P=0, y=1, t=2, h=3). Note: Python is case-sensitive; "th" matches because find searches for lowercase "th" which appears at positions 2-3.

Wait — "Python" has 'P'(0), 'y'(1), 't'(2), 'h'(3), 'o'(4), 'n'(5). So "th" is at indices 2-3. find("th") returns 2.


*Q5. What is the output of "abc" 3?** (a) "abc3" (b) "abcabcabc" (c) Error (d) "abc abc abc"

Answer(b) "abcabcabc"

The operator with a string and an integer repeats the string. "abc" 3 produces "abcabcabc".


Q6. The len("Hello World") returns: (a) 10 (b) 11 (c) 12 (d) Error

Answer(b) 11

len() counts all characters including the space. "Hello World" has 11 characters: H-e-l-l-o-[space]-W-o-r-l-d.


Q7. Which method removes leading and trailing whitespace? (a) trim() (b) strip() (c) remove() (d) clean()

Answer(b) strip()

strip() removes leading and trailing whitespace. lstrip() removes only leading, and rstrip() removes only trailing whitespace.


II. Fill in the Blanks

1. Strings in Python are immutable — they cannot be changed after creation. 2. The len() function returns the number of characters in a string. 3. The index of the first character in a string is 0. 4. The index of the last character in a string of length n is -1 (or n-1). 5. The slicing syntax is string[start:end:step]. 6. "Hello" + "World" results in "HelloWorld" (concatenation without space). 7. "Ha" * 3 results in "HaHaHa" (string repetition). 8. The upper() method converts a string to uppercase. 9. The lower() method converts a string to lowercase. 10. The split() method splits a string into a list based on a delimiter. 11. The join() method joins elements of a list into a string using a separator. 12. "Hello".find("lo") returns 3 (index of 'l' where "lo" starts). 13. "banana".count("a") returns 3. 14. To reverse a string, we use the slicing string[::-1]. 15. The strip() method removes leading and trailing whitespace from a string.


III. True or False (with corrections for false statements)

Q1. Strings in Python are mutable.
Answer

False. Strings in Python are immutable. You cannot change individual characters of a string. Operations like upper(), replace() return new strings; they do not modify the original.


Q2. String indices in Python start at 0.
Answer

True. The first character of a string has index 0, the second has index 1, and so on. Negative indices count from the end (-1 is the last character).


Q3. The replace() method modifies the original string.
Answer

False. The replace() method returns a new string with the replacements. The original string remains unchanged because strings are immutable.

s = "hello"
new_s = s.replace("h", "H")
print(s)     # "hello" — original unchanged
print(new_s) # "Hello" — new string returned

Q4. "5" + "3" returns 8.
Answer

False. "5" + "3" returns "53" — this is string concatenation, not addition. When both operands are strings, + joins them. To add, convert to integers first: int("5") + int("3") = 8.


Q5. Negative indexing in Python starts from -1 for the last character.
Answer

True. In Python, s[-1] refers to the last character, s[-2] refers to the second last, and so on.


Q6. The split() method returns a string.
Answer

False. The split() method returns a list of substrings. For example, "a,b,c".split(",") returns ["a", "b", "c"].


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

True. Triple quotes (''' ''' or """ """) allow strings to span multiple lines, preserving line breaks and formatting.


IV. Match the Following

Column AColumn B
1. upper()(e) Convert to uppercase
2. lower()(a) Convert to lowercase
3. split()(d) Split string into list
4. join()(b) Join list into string
5. find()(f) Return index of substring
6. count()(c) Count occurrences of substring
Answer1–e, 2–a, 3–d, 4–b, 5–f, 6–c

Column AColumn B
1. "Hello"[0](c) 'H'
2. "Hello"[-1](f) 'o'
3. "Hello"[1:4](a) 'ell'
4. "Hello"[::-1](e) 'olleH'
5. len("Hello")(b) 5
6. "Hello" + "World"(d) 'HelloWorld'
Answer1–c, 2–f, 3–a, 4–e, 5–b, 6–d

V. Answer Briefly (2-Mark Questions)

Q1. What is a string? How do you create a string in Python?
Answer

A string is an immutable sequence of characters. Strings can be created using single quotes, double quotes, or triple quotes.

s1 = 'Hello'          # Single quotes
s2 = "World"          # Double quotes
s3 = """Multi
line string"""        # Triple quotes (multi-line)
s4 = 'A'              # Single character (still a string)
print(type(s1))        # <class 'str'>

Q2. Differentiate between string concatenation and string repetition.
Answer
OperationOperatorExampleResult
Concatenation+"Hello" + " World""Hello World"
Repetition*"Ha" * 3"HaHaHa"
  • Concatenation (+) joins two or more strings together
  • Repetition (*) repeats a string a specified number of times
  • Both return a new string (strings are immutable)

Q3. What is string slicing? Give two examples.
Answer

String slicing extracts a portion of a string using the syntax string[start:end:step]. The start index is inclusive, end is exclusive.

s = "PYTHON"

# Example 1: Basic slicing
print(s[1:4])    # "YTH" — from index 1 to 3

# Example 2: Slicing with step
print(s[0:6:2])  # "PTO" — every 2nd character

# Example 3: Omitting start/end
print(s[:3])     # "PYT" — from beginning to index 2
print(s[3:])     # "HON" — from index 3 to end

# Example 4: Reverse string
print(s[::-1])   # "NOHTYP" — reversed

Q4. What is the difference between find() and index() methods?
Answer
Featurefind()index()
ReturnsIndex of first occurrenceIndex of first occurrence
If not foundReturns -1Raises ValueError
Example"hello".find("z") → -1"hello".index("z") → ValueError

Both search for a substring and return the lowest index where it is found. The key difference is how they handle a missing substring: find() returns -1, while index() raises an error.


VI. Answer in Detail (5-Mark Questions)

Q1. Explain string operations in Python (concatenation, repetition, membership, indexing, slicing) with examples.
Answer

1. String Concatenation (+): The + operator joins two or more strings together.

first = "Python"
last = "Programming"
full = first + " " + last
print(full)  # Output: Python Programming

# Note: Cannot concatenate string and number directly
# age = 16
# print("I am " + age + " years old")  # TypeError
# Use str() to convert:
print("I am " + str(16) + " years old")  # I am 16 years old

*2. String Repetition ():* The operator repeats a string a specified number of times.

print("Ha" * 3)    # HaHaHa
print("-" * 30)    # ------------------------------
print("ABC " * 2)  # ABC ABC

3. Membership Operators (in, not in): Check whether a substring exists within a string.

s = "Python Programming"
print("Python" in s)        # True
print("python" in s)        # False (case-sensitive)
print("Java" not in s)     # True
print("gram" in s)          # True

4. String Indexing: Access individual characters using their position (index starts at 0).

s = "HELLO"
print(s[0])    # H — first character
print(s[4])    # O — fifth character
print(s[-1])   # O — last character
print(s[-2])   # L — second last character

5. String Slicing: Extract a substring using string[start:end:step].

s = "PROGRAMMING"

# Basic slicing
print(s[0:7])     # "PROGRAM" — index 0 to 6
print(s[3:8])     # "GRAMM" — index 3 to 7

# Omitting start (default = 0)
print(s[:5])      # "PROGR" — from beginning

# Omitting end (default = end of string)
print(s[5:])      # "MMING" — from index 5 to end

# With step
print(s[0:11:2])  # "PGAI" — every 2nd character

# Negative step (reverse)
print(s[::-1])    # "GNIMMARGORP" — reversed string

# Negative indices
print(s[-5:])     # "MMING" — last 5 characters
6. String Length:
s = "Hello World"
print(len(s))  # 11 (including the space)

Q2. Explain string methods in Python with examples. Write a program to check if a string is a palindrome.
Answer

String Methods:

1. Case Conversion Methods:
s = "hello WORLD"

print(s.upper())       # "HELLO WORLD" — all uppercase
print(s.lower())       # "hello world" — all lowercase
print(s.title())       # "Hello World" — first letter of each word uppercase
print(s.capitalize())  # "Hello world" — first letter uppercase
print(s.swapcase())    # "HELLO world" — swap case of each character
2. Search and Count Methods:
s = "banana"

print(s.find("na"))     # 2 — index of first occurrence
print(s.find("xyz"))    # -1 — not found
print(s.rfind("na"))    # 4 — index from the right
print(s.index("na"))    # 2 — same as find but raises error if not found
print(s.count("a"))     # 3 — number of occurrences
print(s.count("na"))    # 2
print(s.startswith("ban")) # True
print(s.endswith("na"))    # True
3. Strip and Replace Methods:
s = "  Hello World  "

print(s.strip())      # "Hello World" — remove leading/trailing spaces
print(s.lstrip())    # "Hello World  " — remove leading spaces
print(s.rstrip())    # "  Hello World" — remove trailing spaces

text = "I like cats"
print(text.replace("cats", "dogs"))  # "I like dogs"
print(text.replace("i", "I"))        # "I lIke cats" — replaces all occurrences
4. Split and Join Methods:
# Split a string into a list
s = "one,two,three"
print(s.split(","))    # ['one', 'two', 'three']

text = "Hello World"
print(text.split())     # ['Hello', 'World'] — default splits on whitespace

# Join a list into a string
words = ["Python", "is", "fun"]
print(" ".join(words))  # "Python is fun"
print("-".join(words))  # "Python-is-fun"
print("".join(words))   # "Pythonisfun"
5. Checking Methods:
print("hello".isalpha())    # True — all alphabetic
print("12345".isdigit())    # True — all digits
print("hello123".isalnum()) # True — alphabetic or digits
print("   ".isspace())      # True — all whitespace
print("Hello".isupper())   # False — not all uppercase
print("HELLO".isupper())   # True — all uppercase
print("hello".islower())   # True — all lowercase
6. Formatting Methods:
# center(), ljust(), rjust()
s = "Hi"
print(s.center(10))    # "    Hi    " — center in 10-character width
print(s.ljust(10))     # "Hi        " — left justify
print(s.rjust(10))     # "        Hi" — right justify

# zfill()
print("42".zfill(5))   # "00042" — pad with zeros on the left
Answer

Program: Check if a string is a palindrome

# Program to check if a string is a palindrome
def is_palindrome(text):
    # Remove spaces and convert to lowercase for accurate comparison
    cleaned = text.replace(" ", "").lower()

    # Reverse the string using slicing
    reversed_text = cleaned[::-1]

    # Compare original with reversed
    if cleaned == reversed_text:
        return True
    else:
        return False

# Main program
string = input("Enter a string: ")
if is_palindrome(string):
    print(f'"{string}" is a palindrome')
else:
    print(f'"{string}" is not a palindrome')

Output:

Enter a string: Madam "Madam" is a palindrome Enter a string: Hello "Hello" is not a palindrome Enter a string: race car "race car" is a palindrome

Trace for "Madam": cleaned = "madam", reversed = "madam"[::-1] = "madam", "madam" == "madam" → True


Q3. Write Python programs to: (a) Count vowels and consonants in a string (b) Reverse each word in a sentence (c) Check if two strings are anagrams.
Answer

(a) Count vowels and consonants:

# Program to count vowels and consonants
string = input("Enter a string: ")
vowels = 0
consonants = 0
vowel_set = "aeiouAEIOU"

for char in string:
    if char.isalpha():          # Check if character is a letter
        if char in vowel_set:
            vowels += 1
        else:
            consonants += 1

print("Number of vowels:", vowels)
print("Number of consonants:", consonants)

Output:

Enter a string: Hello World Number of vowels: 3 Number of consonants: 7

Trace for "Hello World": H(consonant), e(vowel), l(consonant), l(consonant), o(vowel), (skip-space), W(consonant), o(vowel), r(consonant), l(consonant), d(consonant) → vowels=3, consonants=7

(b) Reverse each word in a sentence:

# Program to reverse each word in a sentence
sentence = input("Enter a sentence: ")
words = sentence.split()          # Split into list of words
reversed_words = []

for word in words:
    reversed_word = word[::-1]    # Reverse each word
    reversed_words.append(reversed_word)

result = " ".join(reversed_words) # Join back with spaces
print("Original :", sentence)
print("Reversed words:", result)

Output:

Enter a sentence: Python is fun Original : Python is fun Reversed words: nohtyP si nuf

Trace: words = ["Python", "is", "fun"] → reversed: ["nohtyP", "si", "nuf"] → joined: "nohtyP si nuf"

(c) Check if two strings are anagrams:

An anagram is a word formed by rearranging the letters of another word. Example: "listen" and "silent" are anagrams.

# Program to check if two strings are anagrams
def are_anagrams(str1, str2):
    # Remove spaces and convert to lowercase
    s1 = str1.replace(" ", "").lower()
    s2 = str2.replace(" ", "").lower()

    # Sort both strings and compare
    if sorted(s1) == sorted(s2):
        return True
    else:
        return False

# Main program
word1 = input("Enter first string: ")
word2 = input("Enter second string: ")

if are_anagrams(word1, word2):
    print(f'"{word1}" and "{word2}" are anagrams')
else:
    print(f'"{word1}" and "{word2}" are not anagrams')

Output:

Enter first string: listen Enter second string: silent "listen" and "silent" are anagrams Enter first string: hello Enter second string: world "hello" and "world" are not anagrams

Trace for "listen" and "silent":

  • s1 = "listen", s2 = "silent"
  • sorted("listen") = ['e', 'i', 'l', 'n', 's', 't']
  • sorted("silent") = ['e', 'i', 'l', 'n', 's', 't']
  • They match → anagrams

Common Mistakes to Avoid

1. Treating strings as mutable — You cannot do s[0] = "H". Strings are immutable. Use s = "H" + s[1:] or s = s.replace(...).

2. Confusing + for numbers vs strings — "5" + "3" is "53" (concatenation), not 8. Use int("5") + int("3") for arithmetic.

3. Off-by-one in slicing — s[1:4] includes index 1 but excludes index 4. It gives characters at indices 1, 2, 3.

4. Case sensitivity in searches — "Hello".find("hello") returns -1 because "Hello" ≠ "hello". Use .lower() first: "Hello".lower().find("hello").

5. Forgetting that string methods return new strings — s.upper() does NOT modify s. It returns a new string. Write s = s.upper() to update the variable.

6. Using index() without error handling — find() returns -1 if not found; index() raises ValueError. Use find() for safe searches.

7. Confusing split() output — split() returns a list, not a string. "a,b,c".split(",") gives ["a", "b", "c"].


Exam Checklist

Before your exam, make sure you can:

  • [ ] Create strings using single, double, and triple quotes
  • [ ] Use positive and negative indexing to access characters
  • [ ] Slice strings with start, end, and step parameters
  • [ ] Reverse a string using [::-1]
  • [ ] Concatenate and repeat strings with + and *
  • [ ] Use membership operators (in, not in) with strings
  • [ ] Apply case conversion methods (upper, lower, title, capitalize, swapcase)
  • [ ] Use search methods (find, rfind, count, startswith, endswith)
  • [ ] Strip whitespace with strip(), lstrip(), rstrip()
  • [ ] Replace substrings with replace()
  • [ ] Split and join strings (split(), join())
  • [ ] Check string properties (isalpha, isdigit, isalnum, isspace)
  • [ ] Write programs: palindrome check, vowel/consonant count, word reversal, anagram check
  • [ ] Explain why strings are immutable with examples

Frequently Asked Questions

A string is an immutable sequence of characters enclosed in single quotes (' '), double quotes (\" \"), or triple quotes (''' ''' or \"\"\" \"\"\"). Example: 'Hello' or \"Python\".