NCERT Solutions — CBSE Class 11 Computer Science: Strings
Complete solved exercises for NCERT Chapter 8 — Strings. Each question includes a clear explanation and working Python code you can run and verify.
How to Use These Solutions
1. Try each question yourself first. Write the code before checking the answer. 2. Run the code in Python and verify the output matches what is shown. 3. Understand why the code works, not just what it does. The logic matters more than memorising syntax. 4. Compare multiple approaches. Some problems can be solved in more than one way — all correct approaches earn full marks.
Key Concepts — Quick Review
- Strings are immutable sequences of characters.
- Positive indexing starts at 0; negative indexing starts at -1.
- Slicing:
s[start:stop:step]— start is inclusive, stop is exclusive. s[::-1]reverses a string.- String methods return new strings; the original is unchanged.
find()returns-1if not found;index()raisesValueError.split()breaks a string into a list;join()combines a list into a string.- Formatting: f-strings (preferred),
.format(), and%operator. - Concatenation with
+; repetition with*; membership within/not in.
Exercise Solutions
Q1. Write a program to check if a string is a palindrome.
def is_palindrome(s):
"""Check if a string is a palindrome (case-insensitive)."""
s = s.lower().replace(" ", "") # ignore case and spaces
return s == s[::-1]
# Test
word = input("Enter a string: ")
if is_palindrome(word):
print(f"'{word}' is a palindrome.")
else:
print(f"'{word}' is not a palindrome.")
Sample output:
Q2. Write a program to count vowels and consonants in a string.
def count_vowels_consonants(s):
"""Count vowels and consonants in a string."""
vowels = "aeiouAEIOU"
v_count = 0
c_count = 0
for char in s:
if char.isalpha():
if char in vowels:
v_count += 1
else:
c_count += 1
return v_count, c_count
# Test
text = input("Enter a string: ")
v, c = count_vowels_consonants(text)
print(f"Vowels : {v}")
print(f"Consonants: {c}")
Sample output:
Q3. Write a program to reverse a string.
def reverse_string(s):
"""Reverse a string using slicing."""
return s[::-1]
# Test
text = input("Enter a string: ")
print(f"Original : {text}")
print(f"Reversed : {reverse_string(text)}")
Sample output:
Q4. Write a program to find a substring in a string using the find() method.
def find_substring(main_str, sub):
"""Find the position of a substring using find()."""
pos = main_str.find(sub)
if pos != -1:
print(f"'{sub}' found at index {pos}")
else:
print(f"'{sub}' not found in the string.")
# Test
main = input("Enter the main string: ")
sub = input("Enter the substring to find: ")
find_substring(main, sub)
Sample output:
Q5. Write a program to replace characters in a string.
def replace_characters(s, old, new):
"""Replace all occurrences of old with new in string s."""
return s.replace(old, new)
# Test
text = "I love Java programming"
result = replace_characters(text, "Java", "Python")
print(f"Original : {text}")
print(f"Modified : {result}")
Output:
Q6. Write a program to split a string and join it back with a different separator.
def split_and_join(text, split_sep, join_sep):
"""Split a string by split_sep and join with join_sep."""
parts = text.split(split_sep)
return join_sep.join(parts)
# Test
csv_data = "red,green,blue,yellow"
result = split_and_join(csv_data, ",", " | ")
print(f"Original : {csv_data}")
print(f"Transformed: {result}")
Output:
Q7. Write a program to demonstrate string formatting using f-strings.
# Student report card using f-strings
name = "Priya"
maths = 95
science = 88
english = 92
total = maths + science + english
average = total / 3
print("=" * 40)
print(f"{'STUDENT REPORT CARD':^40}")
print("=" * 40)
print(f"Name : {name}")
print(f"Maths : {maths}")
print(f"Science : {science}")
print(f"English : {english}")
print("-" * 40)
print(f"Total : {total}")
print(f"Average : {average:.2f}")
print("=" * 40)
Output:
Q8. Write a program to demonstrate string immutability.
def demonstrate_immutability():
"""Show that strings are immutable in Python."""
s = "Hello"
print(f"Original string: {s}")
print(f"ID of original : {id(s)}")
# Trying to change a character directly causes an error
# s[0] = "J" # TypeError: 'str' object does not support item assignment
# "Modifying" a string creates a new object
s = s + " World"
print(f"Modified string: {s}")
print(f"ID of modified : {id(s)}")
print("The IDs are different — a new string object was created.")
# Methods also create new strings
original = "python"
upper_version = original.upper()
print(f"\nOriginal: {original} (id: {id(original)})")
print(f"Upper : {upper_version} (id: {id(upper_version)})")
print("The original string is unchanged.")
demonstrate_immutability()
Output:
Q9. Write a program to count occurrences of each character in a string.
def char_frequency(s):
"""Count the frequency of each character in a string."""
freq = {}
for char in s:
if char in freq:
freq[char] += 1
else:
freq[char] = 1
return freq
# Test
text = "mississippi"
freq = char_frequency(text)
print(f"String: {text}")
print("Character frequencies:")
for char, count in sorted(freq.items()):
print(f" '{char}' : {count}")
Output:
Q10. Write a program to check if two strings are anagrams.
def is_anagram(s1, s2):
"""Check if two strings are anagrams of each other."""
s1_clean = s1.lower().replace(" ", "")
s2_clean = s2.lower().replace(" ", "")
return sorted(s1_clean) == sorted(s2_clean)
# Test
str1 = input("Enter first string: ")
str2 = input("Enter second string: ")
if is_anagram(str1, str2):
print(f"'{str1}' and '{str2}' are anagrams.")
else:
print(f"'{str1}' and '{str2}' are not anagrams.")
Sample output:
Q11. Write a program to extract and display words from a sentence using split().
def extract_words(sentence):
"""Split a sentence into words and display them."""
words = sentence.split()
print(f"Total words: {len(words)}")
for i, word in enumerate(words, 1):
print(f" Word {i}: {word}")
# Test
text = "Python is a powerful programming language"
extract_words(text)
Output:
Q12. Write a program to remove all vowels from a string.
def remove_vowels(s):
"""Remove all vowels from a string."""
vowels = "aeiouAEIOU"
result = ""
for char in s:
if char not in vowels:
result += char
return result
# Test
text = input("Enter a string: ")
print(f"Without vowels: {remove_vowels(text)}")
Sample output:
Q13. Write a program to demonstrate string slicing with different step values.
s = "PYTHONPROGRAMMING"
print(f"Original string : {s}")
print(f"s[0:6] : {s[0:6]}")
print(f"s[6:] : {s[6:]}")
print(f"s[::2] : {s[::2]}")
print(f"s[::-1] : {s[::-1]}")
print(f"s[-5:] : {s[-5:]}")
print(f"s[6:16:2] : {s[6:16:2]}")
print(f"s[::-2] : {s[::-2]}")
Output:
Q14. Write a program to check the data type and properties of a string using string methods.
def check_string(s):
"""Check various properties of a string."""
print(f"String : {s}")
print(f"Length : {len(s)}")
print(f"Is alpha : {s.isalpha()}")
print(f"Is digit : {s.isdigit()}")
print(f"Is alnum : {s.isalnum()}")
print(f"Is upper : {s.isupper()}")
print(f"Is lower : {s.islower()}")
print(f"Is space : {s.isspace()}")
print(f"Starts with 'H': {s.startswith('H')}")
print(f"Ends with '!' : {s.endswith('!')}")
# Test different strings
check_string("Hello123")
print()
check_string("12345")
print()
check_string("hello world")
Output:
Related Chapters
- [CBSE Class 11 Computer Science Chapter 8 — Strings (Chapter Guide)](/class/11/computer-science/cbse-strings)
- [CBSE Class 11 Computer Science Chapter 7 — Functions (Chapter Guide)](/class/11/computer-science/cbse-functions)
- [Functions — NCERT Class 11 Computer Science (Exercise Solutions)](/class/11/computer-science/solutions/cbse-functions-exercise-solutions)
