Current Affairs updated daily
KalviGavaniKalviGavani
Class 11 · CBSE

Strings — NCERT Class 11 Computer Science

Complete NCERT Solutions for CBSE Class 11 Computer Science Chapter 8 — all exercise questions on Python strings, indexing, slicing, methods, formatting, and immutability answered with working code.

Updated 11 June 20268 min read

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 -1 if not found; index() raises ValueError.
  • 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 with in/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:

Enter a string: Madam 'Madam' is a palindrome. Enter a string: Hello 'Hello' is not a palindrome.

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:

Enter a string: KalviGavani Vowels : 5 Consonants: 6

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:

Enter a string: Python Original : Python Reversed : nohtyP

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:

Enter the main string: KalviGavani Enter the substring to find: Gavani 'Gavani' found at index 5

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:

Original : I love Java programming Modified : I love Python programming

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:

Original : red,green,blue,yellow Transformed: red | green | blue | yellow

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:

======================================== STUDENT REPORT CARD ======================================== Name : Priya Maths : 95 Science : 88 English : 92 ---------------------------------------- Total : 275 Average : 91.67 ========================================

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:

Original string: Hello ID of original : 140234567890 Modified string: Hello World ID of modified : 140234567900 The IDs are different — a new string object was created. Original: python (id: 140234567910) Upper : PYTHON (id: 140234567920) The original string is unchanged.

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:

String: mississippi Character frequencies: 'i' : 4 'm' : 1 'p' : 2 's' : 4

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:

Enter first string: Listen Enter second string: Silent 'Listen' and 'Silent' are anagrams.

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:

Total words: 6 Word 1: Python Word 2: is Word 3: a Word 4: powerful Word 5: programming Word 6: language

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:

Enter a string: Beautiful Day Without vowels: Btfl Dy

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:

Original string : PYTHONPROGRAMMING s[0:6] : PYTHON s[6:] : PROGRAMMING s[::2] : PTOPOGMN s[::-1] : GNIMMARGORPNOHTYP s[-5:] : MMING s[6:16:2] : PORMI s[::-2] : GMRROTN

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:

String : Hello123 Length : 8 Is alpha : False Is digit : False Is alnum : True Is upper : False Is lower : False Is space : False Starts with 'H': True Ends with '!' : False String : 12345 Length : 5 Is alpha : False Is digit : True Is alnum : True Is upper : False Is lower : False Is space : False Starts with 'H': False Ends with '!' : False String : hello world Length : 11 Is alpha : False Is alnum : False Is digit : False Is upper : False Is lower : True Is space : False Starts with 'H': False Ends with '!' : False

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)

Frequently Asked Questions

This page has complete NCERT exercise solutions for CBSE Class 11 Computer Science Chapter 8 Strings with working Python code.
← Browse all Class 11 Exercise Solutions

Other question types — same chapter