Class 11 Computer Science Ch 8 Strings in Python NCERT Book Exercise Solution

Chapter – 8 : Strings


Summary (A Quick Recap)


• A string is a sequence of characters enclosed in single, double or triple quotes.

• Indexing is used for accessing individual characters within a string.

• The first character has the index 0 and the last character has the index n-1 where n is the length of the string. The negative indexing ranges from -n to -1.

• Strings in Python are immutable, i.e., a string cannot be changed after it is created.

• Membership operator in takes two strings and returns True if the first string appears as a substring in the second else returns False. Membership operator ‘not in’ does the reverse.

• Retrieving a portion of a string is called slicing. This can be done by specifying an index range. The slice operation str1[n:m] returns the part of
the string str1 starting from index n (inclusive) and ending at m (exclusive).

• Each character of a string can be accessed either using a for loop or while loop.

• There are many built-in functions for working with strings in Python.


Class 11 Computer Science – NCERT Book Exercise Solution

Chapter 8. Strings


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)])

Answer: Computer Science

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

Answer: Scienc

iii. print(mySubject[::2])

Answer: Cmue cec

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

Answer: e

v. print(2*mySubject)

Answer: Computer ScienceComputer Science

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

Answer: eniSrtpo

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

Answer: Computer Science

viii. print(mySubject.swapcase())

Answer: cOMPUTER sCIENCE

ix. print(mySubject.startswith(‘Comp’))

Answer: True

x. print(mySubject.isalpha())

Answer: False

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())

Answer: wz-1,new ganga nagar,new delhi

ii. print(myAddress.upper())

Answer: WZ-1,NEW GANGA NAGAR,NEW DELHI

iii. print(myAddress.count(‘New’))

Answer: 2

iv. print(myAddress.find(‘New’))

Answer: 5

v. print(myAddress.rfind(‘New’))

Answer: 21

vi. print(myAddress.split(‘,’))

Answer: [‘WZ-1’, ‘New Ganga Nagar’, ‘New Delhi’]

vii. print(myAddress.split(‘ ‘))

Answer: [‘WZ-1,New’, ‘Ganga’, ‘Nagar,New’, ‘Delhi’]

viii. print(myAddress.replace(‘New’,’Old’))

Answer: WZ-1,Old Ganga Nagar,Old Delhi

ix. print(myAddress.partition(‘,’))

Answer: (‘WZ-1’, ‘,’, ‘New Ganga Nagar,New Delhi’)

x. print(myAddress.index(‘Agra’))

Answer: ValueError: substring ‘Agra’ 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).

Answer: Function to count characters, alphabets, digits, special symbols and total number of words

def counter(string):
    alpha = 0
    space = 0
    digit = 0
    symbol = 0

    noofchars = len(string)
    
    for ch in string:
        if ch.isalpha():
            alpha = alpha + 1
        elif ch.isdigit():
            digit = digit + 1
        elif ch.isspace():
            space = space + 1
        else:
            symbol = symbol + 1
    print("Number of characters : ", noofchars)
    print("Number of alphabets : ", alpha)
    print("Number of digits : ", digit)
    print("Number of symbols : ", symbol)
    print("Number of spaces : ", space)
    print("Number of words : ", space + 1)


sentence = input("Enter a sentence : ")
counter(sentence)

Output :

Enter a sentence : hello 259 & how ^ you @; ,
Number of characters : 26
Number of alphabets : 11
Number of digits : 3
Number of symbols : 5
Number of spaces : 7
Number of words : 8


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)

Answer: convert a string into the title case

def titlecase(string):
    return string.title()


sentence = input("Enter a sentence : ")
newstr = titlecase(sentence)
print(newstr)

Output:

Enter a sentence : my cs tutorial dot in
My Cs Tutorial Dot In


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.

Answer: Function to Delete Specified Character from a String

def deleteChar(string, character):
    newstring = ""
    for ch in string:
        if ch != character:
            newstring += ch
    return newstring

string = input("Enter a string : ")
char = input("Enter character want to delete : ")

newstr = deleteChar(string, char)

print("After deleting, string is =>")
print(newstr)

Output:

Enter a string : hello my dear students
Enter character want to delete : e

After deleting, string is =>
hllo my dar studnts


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

Answer: Function to return the sum of digits present in this string

def sumofdigits(string):
    sum = 0
    for ch in string:
        if ch.isdigit():
            sum = sum + int(ch)
    return sum


string = "my 23 cs 85 tutorial25"
print("Sum of digits ", sumofdigits(string))

Output:

Sum of digits 25


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.

Answer: Function to replace each space of sentence with hyphen.

#Question 5 : replace space with hypen

def replacespace(sentence):
    newstr =""
    for ch  in sentence:
        if ch.isspace():
            newstr = newstr + "-"
        else:
            newstr = newstr + ch
    return newstr


sentence = input("Enter a sentence : ")
newsentence = replacespace(sentence)
print(newsentence)

Method – II

#Method - II Using String Function

def replacespace2(sentence):
    return sentence.replace(' ','-')

sentence = input("Enter a sentence : ")
newsentence = replacespace2(sentence)
print(newsentence)

Output

Enter a sentence : my cs tutorial
my-cs-tutorial


Class 11 Computer Science – NCERT Book Exercise Solution


You cannot copy content of this page

Scroll to Top