Skip to main content
Chapter 8 of 11
NCERT Solutions

Strings — NCERT Solutions

CBSE · Class 11 · Computer Science

NCERT Solutions for Strings, CBSE Class 11 Computer Science: 7 textbook questions solved step by step. Covers Exercise and Programming Problems.

39 questions80 flashcards8 formulas & key relations5 concepts

Interactive on Super Tutor

Studying Strings? Get the full interactive chapter.

Quizzes, flashcards, AI doubt-solver and a step-by-step study plan — built for NCERT solutions and more.

Free trial, no card needed.

7 Questions Solved · 2 Sections

The first 4 solutions are open to read. The other 3 are free with a Super Tutor account.

Exercise

1Consider the following string mySubject:
mySubject = "Computer Science"
What will be the output of the following string operations:
i. print(mySubject[0:len(mySubject)])
ii. print(mySubject[-7:-1])
iii. print(mySubject[::2])
iv. print(mySubject[len(mySubject)-1])
v. print(2*mySubject)
vi. print(mySubject[::-2])
vii. print(mySubject[:3] + mySubject[3:])
viii. print(mySubject.swapcase())
ix. print(mySubject.startswith('Comp'))
x. print(mySubject.isalpha())
Show solution

Given: mySubject = "Computer Science"

The string has 16 characters (indices 0 to 15).

C o m p u t e r S c i e n c e\text{C o m p u t e r S c i e n c e}
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15\text{0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15}

i. print(mySubject[0:len(mySubject)])

len(mySubject) = 16, so mySubject[0:16] returns the entire string.

Output:

Computer Science

ii. print(mySubject[-7:-1])

Negative index −7-7 corresponds to index 16−7=916 - 7 = 9 (character S) and −1-1 corresponds to index 1515 (exclusive), so characters at indices 9 to 14 are returned: S, c, i, e, n, c.

Output:

Scienc

iii. print(mySubject[::2])

Slice with step 2 picks every alternate character starting from index 0:

  • Indices: 0(C), 2(m), 4(u), 6(e), 8( ), 10(c), 12(e), 14(c)

Output:

Cmue ce

iv. print(mySubject[len(mySubject)-1])

len(mySubject) - 1 = 15, so mySubject[15] = 'e' (last character).

Output:

e

**v. print(2*mySubject)**

The * operator repeats the string 2 times.

Output:

Computer ScienceComputer Science

vi. print(mySubject[::-2])

Slice with step −2-2 starts from the last character (index 15) and moves backwards picking every alternate character:

  • Indices: 15(e), 13(n), 11(i), 9(S), 7(r), 5(t), 3(p), 1(o)

Output:

eniSrtpo

vii. print(mySubject[:3] + mySubject[3:])

mySubject[:3] = "Com" and mySubject[3:] = "puter Science". Concatenating them gives back the full string.

Output:

Computer Science

viii. print(mySubject.swapcase())

swapcase() converts uppercase letters to lowercase and vice versa.

  • C → c, o → O, m → M, p → P, u → U, t → T, e → E, r → R, space stays, S → s, c → C, i → I, e → E, n → N, c → C, e → E

Output:

cOMPUTER sCIENCE

ix. print(mySubject.startswith('Comp'))

startswith() returns True if the string starts with the given prefix. "Computer Science" does start with "Comp".

(Note: The question has a typo startsworth; the correct method is startswith.)

Output:

True

x. print(mySubject.isalpha())

isalpha() returns True only if all characters are alphabetic. "Computer Science" contains a space, so it returns False.

Output:

False
2Consider the following string myAddress:
myAddress = "WZ-1, New Ganga Nagar, New Delhi"
What will be the output of following string operations:
i. print(myAddress.lower())
ii. print(myAddress.upper())
iii. print(myAddress.count('New'))
iv. print(myAddress.find('New'))
v. print(myAddress.rfind('New'))
vi. print(myAddress.split(','))
vii. print(myAddress.split(' '))
viii. print(myAddress.replace('New', 'Old'))
ix. print(myAddress.partition(','))
x. print(myAddress.index('Agra'))
Show solution

Given: myAddress = "WZ-1, New Ganga Nagar, New Delhi"

i. print(myAddress.lower())

lower() converts all characters to lowercase.

Output:

wz-1, new ganga nagar, new delhi

ii. print(myAddress.upper())

upper() converts all characters to uppercase.

Output:

WZ-1, NEW GANGA NAGAR, NEW DELHI

iii. print(myAddress.count('New'))

count() returns the number of non-overlapping occurrences of the substring 'New' in the string. 'New' appears at positions corresponding to "New Ganga" and "New Delhi" — twice.

Output:

2

iv. print(myAddress.find('New'))

find() returns the index of the first occurrence of the substring.

Counting characters in "WZ-1, New Ganga Nagar, New Delhi":

  • W=0, Z=1, -=2, 1=3, ,=4, =5, N=6

First 'New' starts at index 6.

Output:

6

v. print(myAddress.rfind('New'))

rfind() returns the index of the last occurrence of the substring.

Counting: "WZ-1, New Ganga Nagar, " has 23 characters (indices 0–22), so the second 'New' starts at index 23.

Output:

23

vi. print(myAddress.split(','))

split(',') splits the string at every comma and returns a list.

Output:

['WZ-1', ' New Ganga Nagar', ' New Delhi']

vii. print(myAddress.split(' '))

split(' ') splits the string at every single space and returns a list.

Output:

['WZ-1,', 'New', 'Ganga', 'Nagar,', 'New', 'Delhi']

viii. print(myAddress.replace('New', 'Old'))

replace('New', 'Old') replaces all occurrences of 'New' with 'Old'.

Output:

WZ-1, Old Ganga Nagar, Old Delhi

ix. print(myAddress.partition(','))

partition(',') splits the string at the first occurrence of ',' and returns a tuple of three parts: (before separator, separator, after separator).

Output:

('WZ-1', ',', ' New Ganga Nagar, New Delhi')

x. print(myAddress.index('Agra'))

index() raises a ValueError if the substring is not found. 'Agra' does not exist in myAddress.

Output:

ValueError: substring not found

Programming Problems

1Write a program to input line(s) of text from the user until enter is pressed. Count the total number of characters in the text (including white spaces), total number of alphabets, total number of digits, total number of special symbols and total number of words in the given text. (Assume that each word is separated by one space).Show solution

Concept Used:

  • input() to read lines until an empty line (Enter) is pressed.
  • String methods isalpha(), isdigit() to classify characters.
  • A character that is neither alphabetic nor a digit nor a space is a special symbol.
  • Words are counted by splitting on spaces.

Program:

total_chars = 0
total_alpha = 0
total_digits = 0
total_special = 0
total_words = 0

print("Enter lines of text (press Enter on empty line to stop):")

while True:
    line = input()
    if line == "":          # Stop when user presses Enter on empty line
        break
    total_chars += len(line)
    for ch in line:
        if ch.isalpha():
            total_alpha += 1
        elif ch.isdigit():
            total_digits += 1
        elif ch == ' ':
            pass            # spaces counted in total_chars but not special
        else:
            total_special += 1
    # Count words (each word separated by one space)
    words = line.split(' ')
    # Remove empty strings caused by leading/trailing spaces
    words = [w for w in words if w != '']
    total_words += len(words)

print("Total characters (including spaces):", total_chars)
print("Total alphabets                     :", total_alpha)
print("Total digits                        :", total_digits)
print("Total special symbols               :", total_special)
print("Total words                         :", total_words)

Sample Run:

Enter lines of text (press Enter on empty line to stop):
Hello World 123!

Total characters (including spaces): 16
Total alphabets                     : 10
Total digits                        : 3
Total special symbols               : 1
Total words                         : 3
2Write a user defined function to convert a string with more than one word into title case string where string is passed as parameter. (Title case means that the first letter of each word is capitalised)Show solution

Concept Used:

  • Split the string into individual words using split().
  • Capitalise the first letter of each word using capitalize() (or manually using indexing).
  • Join the words back using join().

Program:

def toTitleCase(sentence):
    """
    Converts a string to title case.
    Parameter: sentence (str) - input string
    Returns  : title-cased string
    """
    words = sentence.split()          # Split on whitespace
    title_words = []
    for word in words:
        # Capitalise first letter, lowercase the rest
        title_word = word[0].upper() + word[1:].lower()
        title_words.append(title_word)
    return ' '.join(title_words)

# --- Driver code ---
text = input("Enter a string: ")
result = toTitleCase(text)
print("Title Case String:", result)

Sample Run:

Enter a string: hello world from python
Title Case String: Hello World From Python

Note: Python also provides a built-in str.title() method, but the above function demonstrates the logic manually as expected in a board exam.

3Write a function deleteChar() which takes two parameters — one is a string and other is a character. The function should create a new string after deleting all occurrences of the character from the string and return the new string.

Free with a Super Tutor account

4Input a string having some digits. Write a function to return the sum of digits present in this string.

Free with a Super Tutor account

5Write a function that takes a sentence as an input parameter where each word in the sentence is separated by a space. The function should replace each blank with a hyphen and then return the modified sentence.

Free with a Super Tutor account

3 more solved questions in Strings

They are free with a Super Tutor account, along with practice quizzes and flashcards for this chapter. Free to start, no card needed.

Frequently Asked Questions

What are the important topics in Strings for CBSE Class 11 Computer Science?
Key topics in Strings include String Basics and Creation, Indexing and len(), String Operations, Slicing and Reversing. Study these first, then practise questions on each for Class 11 exams.
Are these NCERT Solutions for Strings free?
The first 4 of the 7 solutions on this page are open to read. The other 3 are free with a Super Tutor account — signing up is free and needs no card.
How should I revise Strings for Class 11 exams?
Learn the core ideas first, then work through the 39 practice questions on Strings. Revise definitions regularly and use flashcards for quick recall before the exam.

Sources & Official References

Content is aligned to the official syllabus. Refer to the board website for the latest curriculum.

For serious students

Get the full Strings chapter — start free.

Quizzes, flashcards, an AI doubt solver and a study plan for CBSE Class 11 Computer Science. Free to start, no card needed.