This page contains the NCERT Computer Science class 11 chapter 8 Strings. You can find the solutions for the chapter 8 of NCERT class 11 Computer Science Exercise. So is the case if you are looking for NCERT class 11 Computer Science related topic Strings questions and answers for the Exercise
Exercise
1. Consider 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())Let:
`mySubject = "Computer Science"` (Length = 16)i.
print(mySubject[0:len(mySubject)])
Explanation: Prints the full string using a complete slice.
Output:
Computer Science
ii.
print(mySubject[-7:-1])
Explanation: Extracts characters from index -7 up to -2.
Output:
Scienc
iii.
print(mySubject[::2])
Explanation: Prints every second character (step = 2).
Output:
Cmue cec
iv.
print(mySubject[len(mySubject)-1])
Explanation: Accesses the last character of the string.
Output:
e
v.
print(2*mySubject)
Explanation: Repeats the string twice using multiplication.
Output:
Computer ScienceComputer Science
vi.
print(mySubject[::-2])
Explanation: Prints the string in reverse, skipping every second character.
Output:
eniSrtpo
vii.
print(mySubject[:3] + mySubject[3:])
Explanation: Concatenates two slices that form the original string.
Output:
Computer Science
viii.
print(mySubject.swapcase())
Explanation: Swaps lowercase letters to uppercase and vice versa.
Output:
cOMPUTER sCIENCE
ix.
print(mySubject.startswith('Comp'))
Explanation: Checks if the string starts with “Comp”.
Output:
True
x.
print(mySubject.isalpha())
Explanation: Checks whether all characters are alphabets.
Output:
False
(Because it contains a space.)
2. Consider 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'))Let:
`myAddress = "WZ-1,New Ganga Nagar,New Delhi"`i.
print(myAddress.lower())
Explanation: Converts the entire string to lowercase.
Output:
wz-1,new ganga nagar,new delhi
ii.
print(myAddress.upper())
Explanation: Converts the entire string to uppercase.
Output:
WZ-1,NEW GANGA NAGAR,NEW DELHI
iii.
print(myAddress.count('New'))
Explanation: Counts how many times “New” appears.
Output:
2
iv.
print(myAddress.find('New'))
Explanation: Finds the first index of “New”.
Output:
5
v.
print(myAddress.rfind('New'))
Explanation: Finds the last index of “New”.
Output:
21
vi.
print(myAddress.split(','))
Explanation: Splits the string using comma as the separator.
Output:
['WZ-1', 'New Ganga Nagar', 'New Delhi']
vii.
print(myAddress.split(' '))
Explanation: Splits the string using space as the separator.
Output:
['WZ-1,New', 'Ganga', 'Nagar,New', 'Delhi']
viii.
print(myAddress.replace('New','Old'))
Explanation: Replaces all occurrences of “New” with “Old”.
Output:
WZ-1,Old Ganga Nagar,Old Delhi
ix.
print(myAddress.partition(','))
Explanation: Splits the string into three parts at the first comma.
Output:
('WZ-1', ',', 'New Ganga Nagar,New Delhi')
x.
print(myAddress.index('Agra'))
Explanation: Searches for “Agra” and raises an error if not found.
Output:
ValueError: substring not found
Programming Problems
1. Write 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).
# Program 1: Text analysis (characters, alphabets, digits, special symbols, words)
def analyze_text(text: str) -> dict:
"""
Returns counts of:
- total_chars (includes spaces)
- alphabets
- digits
- special_symbols (not alphabet, not digit, not whitespace)
- words (assumes words separated by one space)
"""
total_chars = len(text)
alphabets = 0
digits = 0
special_symbols = 0
for ch in text:
if ch.isalpha():
alphabets += 1
elif ch.isdigit():
digits += 1
elif ch.isspace():
# whitespace is counted in total_chars, but not in special_symbols
pass
else:
special_symbols += 1
# Assuming words are separated by one space.
# Using strip() to avoid counting leading/trailing spaces as extra words.
if text.strip() == "":
words = 0
else:
words = len(text.strip().split(" "))
return {
"total_chars": total_chars,
"alphabets": alphabets,
"digits": digits,
"special_symbols": special_symbols,
"words": words
}
# ---- Main Program ----
# "until enter is pressed" -> user enters one full line and presses Enter
text = input("Enter text: ")
result = analyze_text(text)
print("\n--- Result ---")
print("Total characters (including spaces):", result["total_chars"])
print("Total alphabets:", result["alphabets"])
print("Total digits:", result["digits"])
print("Total special symbols:", result["special_symbols"])
print("Total words:", result["words"])
Input entered:
Hello World! 123
Output:
Enter text: Hello World! 123
--- Result ---
Total characters (including spaces): 16
Total alphabets: 10
Total digits: 3
Total special symbols: 1
Total words: 3
2. Write 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)
# Program 2: User-defined function to convert a sentence to Title Case
def to_title_case(sentence: str) -> str:
"""
Converts a multi-word string into title case:
first letter of each word -> uppercase, remaining -> lowercase.
Example: "hELLo worLD" -> "Hello World"
"""
words = sentence.split(" ") # assuming one space between words
title_words = []
for w in words:
if w == "":
# Safety: in case there are extra spaces (not expected as per question)
title_words.append("")
else:
title_words.append(w[0].upper() + w[1:].lower())
return " ".join(title_words)
# ---- Main Program ----
st = input("Enter a string: ")
print("Title Case:", to_title_case(st))
Console execution (example input: hELLo worLD)
Enter a string: hELLo worLD
Title Case: Hello World
Another example (input: this is a test)
Enter a string: this is a test
Title Case: This Is A Test
3. Write 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.
# Program 3: deleteChar() - remove all occurrences of a character from a string
def deleteChar(st: str, ch: str) -> str:
"""
Returns a new string after deleting all occurrences of character ch from st.
"""
newstr = ""
for c in st:
if c != ch:
newstr += c
return newstr
# ---- Main Program ----
st = input("Enter a string: ")
ch = input("Enter the character to delete: ")
# If user types more than one character, we take the first one.
ch = ch[0] if ch else ""
print("New string:", deleteChar(st, ch))
Run 1
Enter a string: hello world
Enter the character to delete: l
New string: heo word
Run 2
Enter a string: banana
Enter the character to delete: a
New string: bnn
Run 3 (user types more than 1 character → program uses only the first)
Enter a string: hello
Enter the character to delete: lo
New string: he
(Because only l is taken from “lo”.)
Run 4 (edge case: empty delete character input)
Enter a string: test
Enter the character to delete:
New string: test
4. Input a string having some digits. Write a function to return the sum of digits present in this string.
# Program 4: Sum of digits present in a string
def sum_of_digits(st: str) -> int:
"""
Extracts digits from the string and returns their sum.
Example: "a2b9x" -> 2 + 9 = 11
"""
total = 0
for ch in st:
if ch.isdigit():
total += int(ch)
return total
# ---- Main Program ----
st = input("Enter a string with digits: ")
print("Sum of digits:", sum_of_digits(st))
Example run (input: a2b9x):
Enter a string with digits: a2b9x
Sum of digits: 11
5. Write 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.
# Program 5: Replace blanks (spaces) with hyphen
def blanks_to_hyphen(sentence: str) -> str:
"""
Replaces each space ' ' with a hyphen '-'.
Example: "I love Python" -> "I-love-Python"
"""
return sentence.replace(" ", "-")
# ---- Main Program ----
st = input("Enter a sentence: ")
print("Modified sentence:", blanks_to_hyphen(st))
Output:
Enter a sentence: I love Python
Modified sentence: I-love-Python