KnowledgeBoat Logo
OPEN IN APP

Chapter 6

Strings in Python

Class 11 - Computer Science with Python Preeti Arora



Fill in the Blanks

Question 1

A string is a Sequence of characters.

Question 2

Positive subscript helps in accessing the string from the beginning.

Question 3

Negative subscript helps in accessing the string from the end.

Question 4

'+' operator concatenates the strings on both sides of the operator.

Question 5

The find() method returns the lowest index of the substring if it is found in the given string.

Question 6

capitalize() function returns the exact copy of the string with the first letter in uppercase.

Question 7

Strings cannot be modified as they are immutable data types.

Question 8

The sequential accessing of each of the elements in a string is called string traversal.

Question 9

in membership operator returns True if a character or substring exists in the given string.

Question 10

String slice is a part of the string containing some contiguous characters from the string.

Question 11

The find() function returns -1 when substring is not found in the main string.

Question 12

count() function is used to count how many times an element has occurred in a list.

Question 13

startswith() function returns True if the given string starts with the specified substring, else returns False.

State True or False

Question 1

An empty string is a string that has zero number of characters.

Answer

True

Reason — An empty string is a string without any characters inside, having length zero.

Question 2

The last index number of string is (length-1) or -1.

Answer

True

Reason — The last index of a string is (length - 1). Strings also support negative indexing, where -1 refers to the last character.

Question 3

"abc" * 2 will give abc*2 as output.

Answer

False

Reason — In Python, the * operator, when used with a string and an integer, repeats the string the specified number of times. So, "abc" * 2 means the string "abc" is repeated twice, resulting in "abcabc".

Question 4

Multiplication operator (*) replicates the string.

Answer

True

Reason — Multiplication operator (*) creates a new string by repeating multiple copies of the same string.

Question 5

We can combine two strings with the help of '&' operator.

Answer

False

Reason — We can combine two strings with the help of '+' operator.

Question 6

When we compare "A" != "a", it will give True as an output.

Answer

True

Reason — In Python, string comparison is based on the ASCII or Unicode values of the characters. The ASCII value of "A" is 65, while the ASCII value of "a" is 97. Since these values are different, the comparison "A" != "a" evaluates to True.

Question 7

String allows forward and backward type of indexing.

Answer

True

Reason — Strings in Python support both forward and backward indexing. Forward indexing starts from 0 and goes up to the (length - 1), while backward indexing starts from -1 (the last character) and goes up to the negative length of the string.

Question 8

In Python, asc() function returns corresponding Unicode value of a character.

Answer

False

Reason — The ord() function is used to return the corresponding Unicode value of a character.

Question 9

The size of "\\" is 2.

Answer

True

Reason — An escape sequence character is represented as a string with one byte of memory. Therefore, "\\" is a string with two backslashes, which uses 2 bytes of memory.

Question 10

Multiple line string created with the help of triple quotes will include end line character in the length.

Answer

False

Reason — Multiple line string created with the help of triple quotes will include newline character ('\n') in the length.

Question 11

A string is a mutable sequence of one or more characters.

Answer

False

Reason — Strings are immutable means that the content of the string cannot be changed after it is created.

Multiple Choice Questions

Question 1

Which of the following is not a Python legal string operation?

  1. 'abc' + 'abc'
  2. 'abc' *3
  3. 'abc' + 3
  4. 'abc'.lower()

Answer

'abc' + 3

Reason'abc' + 3 is not a legal string operation in Python. The operands of + operator should be both string or both numeric. Here one operand is string and other is numeric. This is not allowed in Python.

Question 2

In Python string, + and * represent which of the following operations?

  1. Concatenation, Replication
  2. Addition, Multiplication
  3. Neither (i) nor (ii)
  4. Both (i) and (ii)

Answer

Concatenation, Replication

Reason — In Python strings, the + operator is used for concatenation, which means combining two strings into one. The * operator is used for replication, which means repeating the string a specified number of times.

Question 3

Which of following is not a valid string operation?

  1. Slicing
  2. Concatenation
  3. Repetition
  4. Floor

Answer

Floor

Reason — In Python, valid string operations include slicing, concatenation, and repetition. However, "floor" is not a valid string operation.

Question 4

How many times is the word "Python" printed in the following statement?

s = 'I love Python'
for ch in s[3:8]:
    print('Python')
  1. 11 times
  2. 8 times
  3. 3 times
  4. 5 times

Answer

5 times

Reason — The slice s[3:8] consists of 5 characters, and the for loop prints 'Python' for each character in the substring, resulting in 'Python' being printed 5 times.

Question 5

Which of the following is the correct syntax of String Slicing?

  1. String_name [start : end]
  2. String_name [start : step]
  3. String_name [step : end]
  4. String_name [step : start]

Answer

String_name [start : end]

Reason — In Python, the correct syntax for string slicing is String_name[start:end], where 'start' is the index where the slice begins, and 'end' is the index where the slice ends.

Question 6

What is the correct Python code to display the last four characters of "Digital India"?

  1. str [-4 :]
  2. str [4 :]
  3. str [*4 :]
  4. str [/4 : ]

Answer

str [-4 :]

Reason — The Python code to display the last four characters of "Digital India" is str[-4:]. The negative index -4 starts the slice from the fourth-to-last character to the end of the string.

Question 7

What will be the output of the following code?

str1= "I love Python."
strlen = len(str1)
print(strlen)
  1. 9
  2. 29
  3. 14
  4. 3

Answer

14

Reason — The len() function returns the length of the string, which includes all characters, spaces, and punctuation. For the string "I love Python.", the length is 14 characters. Thus, len(str1) returns 14.

Question 8

What will be the output of the following code?

Str1= 'My name is Nandini '
Str2 = Str1[3:7]
strlen = len(Str2)
print(strlen)
  1. 4
  2. 14
  3. 24
  4. 34

Answer

4

Reason — The slice Str1[3:7] extracts characters from index 3 to 6 of the string 'My name is Nandini ', which results in 'name'. The length of this substring is 4 characters. Thus, len(Str2) returns 4.

Question 9

Which method removes all the trailing whitespaces from the right of the string?

  1. tolower()
  2. upper()
  3. Istrip()
  4. rstrip()

Answer

rstrip()

Reason — The rstrip() function removes all the trailing whitespaces from the right of the string.

Question 10

To concatenate means to ............... .

  1. replicate
  2. join
  3. split
  4. multiply

Answer

join

Reason — To concatenate means to join. The '+' operator joins or concatenates strings written on both sides of the operator and creates a new string.

Question 11

............... function will always return tuple of 3 elements.

  1. index()
  2. split()
  3. partition()
  4. strip()

Answer

partition()

Reason — The partition() function is used to split the given string using the specified separator and returns a tuple with three parts: substring before the separator, separator itself, a substring after the separator.

Question 12

What will be the output of the following code?

A = 'Virtual Reality'
A.replace('Virtual', 'Augmented')
  1. Virtual Augmented
  2. Reality Augmented
  3. Augmented Virtual
  4. Augmented Reality

Answer

Augmented Reality

Reason — The replace() method creates and returns a new string with the specified substring replaced, without altering the original string. In this case, 'Virtual' is replaced by 'Augmented', resulting in 'Augmented Reality'.

Question 13

What will be the output of the following?

print("ComputerScience".split("er", 2))
  1. ["Computer", "Science"]
  2. ["Comput", "Science"]
  3. ["Comput", "erScience"]
  4. ["Comput", "er", "Science"]

Answer

["Comput", "Science"]

Reason — The split() method splits a string into a list of substrings based on the specified delimiter. In this case, "er" is the delimiter. The second argument 2 is the maximum number of splits to be made. "ComputerScience" is split using "er" as the delimiter. The first occurrence of "er" splits "ComputerScience" into "Comput" and "Science". Since the 2 splits limit is applied, it does not continue searching for additional delimiters beyond the first one. Thus, the output is ['Comput', 'Science'].

Question 14

What is the ASCII equivalent decimal no. for 'Y'?

  1. 87
  2. 88
  3. 89
  4. 90

Answer

89

Reason — The ASCII equivalent decimal number for 'Y' is 89.

Question 15

STR = "RGBCOLOR"
colors = list(STR)

How do we delete 'B' in given List colors?

  1. del colors[2]
  2. colors.remove("B")
  3. colors.pop(2)
  4. All of these

Answer

All of these

Reason — The statement STR = "RGBCOLOR" assigns the string "RGBCOLOR" to the variable STR, and colors = list(STR) converts this string into a list of its individual characters. As a result, colors will be ['R', 'G', 'B', 'C', 'O', 'L', 'O', 'R']. All of the methods mentioned can be used to delete 'B' from the list colors. Using del colors[2] removes the item at index 2, which is 'B'. The colors.remove("B") method removes the first occurrence of the value 'B'. Similarly, colors.pop(2) removes and returns the item at index 2, which is 'B'.

Question 16

Which of the following will give "Simon" as output?

str1 = "Hari,Simon,Vinod"
  1. print(str1[-7:-12])
  2. print(str1[-11:-7])
  3. print(str1[-11:-6])
  4. print(str1[-7:-11])

Answer

print(str1[-11:-6])

Reason — The correct statement to get "Simon" as output is print(str1[-11:-6]). In the string str1, the slice [-11:-6] extracts the substring starting from the character at index -11 (which is 'S' in "Simon") up to the character at index -5, thus resulting in "Simon".

Assertions and Reasons

Question 1

Assertion(A): S1 ='CoMPuter SciENce'
S1[0] = S1[0].lower()

The above code will generate error.

Reasoning(R): String is immutable by default. The contents of the string cannot be changed after it has been created.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

Both A and R are true and R is the correct explanation of A.

Explanation
In Python, strings are immutable, meaning that once a string is created, its contents cannot be modified. The statement S1[0] = S1[0].lower() attempts to change the first character of the string S1 to lowercase, but since strings are immutable, this operation will result in an Error.

Question 2

Assertion (A): print('INDIA'.capitalize())
This command on execution shall display the output as 'India'.

Reasoning (R): The capitalize() method returns a string where the first character is uppercase and the rest is lower case.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

Both A and R are true and R is the correct explanation of A.

Explanation
The capitalize() method in Python converts the first character of a string to uppercase and the rest of the characters to lowercase. The statement 'INDIA'.capitalize() will return "India" because it converts the first letter to uppercase and all other letters to lowercase.

Question 3

Assertion (A): The process of repeating a set of elements in a string is termed as replication.

Reasoning (R): Repetition allows us to repeat the given string using (*) operator along with a number that specifies the number of replications.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

Both A and R are true and R is the correct explanation of A.

Explanation
In Python, the process of repeating a string multiple times is referred to as repetition or replication. This is done using the (*) operator, where a string is multiplied by an integer to create a new string that repeats the original string the specified number of times.

Question 4

Assertion (A): In Python, the strings are mutable.

Reasoning (R): In strings, the values are enclosed inside double or single quotes.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

A is false but R is true.

Explanation
In Python, strings are immutable, meaning their content cannot be changed after they are created. Strings in Python are defined by enclosing text within single (' ') or double (" ") quotes.

Question 5

Assertion (A): Slicing a string involves extracting substring(s) from a given string.

Reasoning (R): Slicing does not require start and end index value of the string.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

A is true but R is false.

Explanation
String slicing is the process of extracting a part of a string (substring) using a specified range of indices. A substring can be extracted from a string using the slice operator, which includes two indices in square brackets separated by a colon ([:]). The syntax is string_name[start:end:step].

Question 6

Assertion (A): The swapcase() function converts an input string into a toggle case.

Reasoning (R): The swapcase() function converts all uppercase characters to lowercase and vice versa of the given string and returns it.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

Both A and R are true and R is the correct explanation of A.

Explanation
The swapcase() function converts an input string into toggle case. It converts all uppercase characters to lowercase and all lowercase characters to uppercase in the given string and then returns the modified string.

Question 7

Assertion (A): Indexing in a string is defined as positive and negative indexing.

Reasoning (R): In forward and backward indexing, the indices start with 1st index.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

A is true but R is false.

Explanation
Indexing in a string can be defined as positive and negative indexing. In Python, positive indexing starts from 0 and moves to the right, while negative indexing starts from -1 and moves to the left.

Question 8

Assertion (A): The following code snippet on execution shall return the output as: False True

str1 "Mission 999"  
str2 = "999"  
print(str1.isdigit(), str2.isdigit())

Reasoning (R): isdigit() function checks for the presence of all the digits in an inputted string.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

Both A and R are true and R is the correct explanation of A.

Explanation
The isdigit() function returns True if the string contains only digits, otherwise False. In the given code, str1 contains both alphabets and digits, so str1.isdigit() will return False. On the other hand, str2 contains only digits, so str2.isdigit() will return True.

Solutions to Unsolved Questions

Question 1

How does '*' operator behave on strings?

Answer

The * operator creates a new string by repeating multiple copies of the same string.

For example,

string = "abc"
repeated_string = string * 3
print(repeated_string)
Output
abcabcabc

In the above example, the string "abc" is repeated 3 times to produce "abcabcabc".

Question 2

Explain function split() with an example.

Answer

The split() function breaks up a string at the specified separator and returns a list of substrings. The syntax is str.split([separator, [maxsplit]]). The split() method takes a maximum of 2 parameters:

  1. separator (optional) — The separator is a delimiter. The string splits at the specified separator. If the separator is not specified, any whitespace (space, newline, etc.) string is a separator.

  2. maxsplit (optional) — The maxsplit defines the maximum number of splits. The default value of maxsplit is -1, which means no limit on the number of splits.

For example,

x = "blue;red;green"
print(x.split(";"))
Output
['blue', 'red', 'green']

Question 3

How many times is the word 'HELLO' printed in the following statement?

s = "python rocks"
for ch in s:
    print ("Hello")

Answer

The word 'Hello' is printed 12 times in the given Python code because the string s = "python rocks" contains 12 characters. The for loop iterates through each character in the string, printing 'Hello' once for each character, resulting in a total of 12 prints.

Question 4

Write the output of the following:

>>> x = "hello"
>>> print(x[1:-2])

Answer

Output
el
Explanation

The statement x[1:-2] slices the string "hello" starting from index 1 up to index -3. This results in the substring "el", so print(x[1:-2]) outputs "el".

Question 5(a)

Write the output of the following:

string = "Hello Madam, I love Tutorials"
substring = "Madam"
if string.find(substring) != -1:
    print("Python found the substring!")
else:
    print("Python did NOT find the substring!")

Answer

Output
Python found the substring!
Explanation

The code checks if the substring "Madam" exists in the string "Hello Madam, I love Tutorials" using the find() method. Since "Madam" is present in the string, find() returns the starting index of "Madam", which is not -1. Therefore, the condition string.find(substring) != -1 evaluates to True, and the code prints "Python found the substring!".

Question 5(b)

Write the output of the following:

s = "Strings in Python"
print(s.capitalize())
print(s.title())
s6 = s.replace("in", "data type")
print(s6)

Answer

Output
Strings in python
Strings In Python
Strdata typegs data type Python
Explanation

The s.capitalize() method capitalizes the first letter of the string and converts the rest to lowercase, resulting in "Strings in python". The s.title() method capitalizes the first letter of each word, producing "Strings In Python". The s.replace("in", "data type") method replaces occurrences of "in" with "data type", giving "Strdata typegs data type Python" as output.

Question 6

Find the output of the following:

word = 'work hard'
result = word.find('work')
print("Substring, 'work', found at index:", result)
result = word.find('har') 
print("Substring, 'har ' ,found at index:", result)
if (word.find('pawan') != -1):
    print("Contains given substring ")
else: 
    print("Doesn't contain given substring")

Answer

Output
Substring, 'work', found at index: 0
Substring, 'har ' ,found at index: 5
Doesn't contain given substring
Explanation

The code first searches for the substring 'work' in 'work hard' using find(), which is located at index 0, so it prints "Substring, 'work', found at index: 0". Next, it searches for 'har', which starts at index 5, resulting in "Substring, 'har ', found at index: 5". Finally, it checks if 'pawan' is in the string; since it is not, find() returns -1, and the code prints "Doesn't contain given substring".

Question 7

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

Answer

(i) Computer Science

(ii) Scienc

(iii) Cmue cec

(iv) e

(v) Computer ScienceComputer Science

(vi) eniSrtpo

(vii) Computer Science

(viii) cOMPUTER sCIENCE

(ix) True

(x) False

Explanation

(i) It slices the string from index 0 to the length of the string, which returns the entire string.

(ii) It uses backward slicing to extract a substring starting from the 7th character from the end to the second-to-last character.

(iii) It slices the string by taking every second character starting from index 0.

(iv) The code first calculates the length of the string mySubject, which is 16. It then accesses the character at the index len(mySubject) - 1, which is 15, corresponding to the last character of the string, 'e'.

(v) It multiplies the string mySubject by 2, which duplicates the string.

(vi) It slices the string mySubject with a step of -2, which reverses the string and selects every second character.

(vii) The code print(mySubject[:3] + mySubject[3:]) combines two slices of the string mySubject. mySubject[:3] extracts the first three characters, and mySubject[3:] extracts the substring from the fourth character to the end. Concatenating these substrings prints 'Computer Science'.

(viii) The swapcase() function converts all uppercase letters in the string mySubject to lowercase and all lowercase letters to uppercase.

(ix) The startswith() function checks if the string mySubject starts with the substring 'Comp'. It returns True because mySubject begins with 'Comp'.

(x) The isalpha() function checks if all characters in the string mySubject are alphabetic. It returns False because the string contains spaces, which are not alphabetic characters.

Question 8

Write the Python statement and the output for the following:

(a) Find the third occurrence of 'e' in 'sequence'.

(b) Change the case of each letter in string 'FuNcTioN'.

(c) Whether 'Z' exists in string 'School' or not.

Answer

(a)

s = 'sequence'
index = s.find('e', s.find('e', s.find('e') + 1) + 1)
print(index)
Output
7

(b)

s = 'FuNcTioN'
print(s.swapcase())
Output
fUnCtIOn

(c)

s = 'School'
print('Z' in s)
Output
False

Question 9

Consider the string str1 = "Global Warming".

Write statements in Python to implement the following:

(a) To display the last four characters.

(b) To replace all the occurrences of letter 'a' in the string with "*".

Answer

(a)

str1 = "Global Warming"
last_four = str1[-4:]
print(last_four)
Output
ming

(b)

str1 = "Global Warming"
replaced_str = str1.replace('a', '*')
print(replaced_str)
Output
Glob*l W*rming

Question 10

What will be the output of the following code?

Text = "Mind@Work!" 
ln = len(Text)
nText = ""
for i in range(0, ln):
    if Text[i].isupper():
        nText = nText + Text[i].lower()
    elif Text[i].isalpha(): 
        nText = nText + Text[i].upper() 
else: 
    nText = nText + 'A'
print(nText)

Answer

Output
mINDwORKA
Explanation

Below is the detailed step by step explanation of the program:

Initialization

Text = "Mind@Work!"
ln = len(Text)
nText = ""
  • Text is initialized with the string "Mind@Work!".
  • ln holds the length of Text, which is 10 in this case.
  • nText is initialized as an empty string, which will hold the transformed characters.

Loop through each character

for i in range(0, ln):
    if Text[i].isupper():
        nText = nText + Text[i].lower()
    elif Text[i].isalpha(): 
        nText = nText + Text[i].upper()
else: 
    nText = nText + 'A'
  • A for loop iterates over each index i from 0 to ln-1 (i.e., 0 to 9).

Conditions within the loop:

  1. Text[i].isupper(): Checks if the character at index i in the string Text is an uppercase letter.

    • If true, it converts the character to lowercase using Text[i].lower() and appends it to nText.
  2. elif Text[i].isalpha(): Checks if the character at index i in the string Text is an alphabetic letter (either uppercase or lowercase).

    • If the character is alphabetic but not uppercase, it converts the character to uppercase using Text[i].upper() and appends it to nText.

else statement of loop:

  • The else statement in this context is associated with the for loop, meaning it executes after the loop has completed iterating over all the indices.
  • nText = nText + 'A' appends the character 'A' to the end of nText.

Printing the result

print(nText)
  • This line prints the final value of nText.

Step-by-Step Execution

1. Initial States:

  • Text = "Mind@Work!"
  • ln = 10
  • nText = ""

2. Loop Iterations:

IndexCharacterConditionTransformationnText
0'M'isupper() is True'm'"m"
1'i'isalpha() is True'I'"mI"
2'n'isalpha() is True'N'"mIN"
3'd'isalpha() is True'D'"mIND"
4'@'neither condition is True-"mIND"
5'W'isupper() is True'w'"mINDw"
6'o'isalpha() is True'O'"mINDwO"
7'r'isalpha() is True'R'"mINDwOR"
8'k'isalpha() is True'K'"mINDwORK"
9'!'neither condition is True-"mINDwORK"

3. Post Loop Execution:

  • The loop is complete, so the else statement appends 'A' to nText.
  • nText = "mINDwORK" + "A" = "mINDwORKA"

4. Print Output:

  • print(nText) outputs "mINDwORKA".

Question 11

Input the string 'My School'. Write a script to partition the string at the occurrence of letter 'h'.

Solution
s = "My School"
print(s.partition('h'))
Output
('My Sc', 'h', 'ool')

Question 12

Write a program to convert a string with more than one word into titlecase string where string is passed as parameter. (Titlecase means that the first letter of each word is capitalized.)

Solution
s = input("Enter a string: ")
s1 = s.title()
print(s1)
Output
Enter a string: python programming is fun
Python Programming Is Fun

Question 13

Write a program 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.

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

modified_sentence = sentence.replace(' ', '-')

print(modified_sentence)
Output
Enter a sentence: Innovation drives progress
Innovation-drives-progress

Question 14

Write a script to partition the string 'INSTITUTE' at the occurrence of letter 'T'.

Solution
string = 'INSTITUTE'
parts = string.partition('T')
print(parts)
Output
('INS', 'T', 'ITUTE')

Question 15

What will be the output of the following programming code?

str = "My Python Programming"
print (str[-5:-1])
print (str[1:5])
print (str[:-4])
print (str[0:])
print (str[:13-4])
print (str[:3])

Answer

Output
mmin
y Py
My Python Program
My Python Programming
My Python
My 
Explanation
  1. str[-5:-1] extracts the substring from the 5th last character up to, but not including, the last character: "mmin".
  2. str[1:5] extracts the substring from index 1 to 4: "y Py".
  3. str[:-4] extracts the substring from the beginning up to, but not including, the last 4 characters.
  4. str[0:] extracts the substring from index 0 to the end.
  5. str[:13-4] is equivalent to str[:9], which extracts the substring from the beginning up to, but not including, index 9: "My Python".
  6. str[:3] extracts the substring from the beginning up to, but not including, index 3: "My ".

Question 16

Write a program to count the number of each vowel in a given string.

Solution
input_string = input("Enter a string: ")
vowel_count = {'a': 0, 'e': 0, 'i': 0, 'o': 0, 'u': 0}
input_string = input_string.lower()

for char in input_string:
    if char in vowel_count:
        vowel_count[char] += 1

print("Vowel counts:", vowel_count)
Output
Enter a string: The quick brown fox jumps over the lazy dog.
Vowel counts: {'a': 1, 'e': 3, 'i': 1, 'o': 4, 'u': 2}

Question 17

Write a program that reads a line, then counts how many times the word 'is' appears in the line and displays the count.

Solution
line = input("Enter a line: ")
line = line.lower()
words = line.split()
count = words.count('is')
print("The word 'is' appears", count, "times.")
Output
Enter a line: The project is ambitious, and its success is dependent on how well it is managed and executed.
The word 'is' appears 3 times.

Question 18

Write a program to remove 'i' (if any) from a string.

Solution
input_string = input("Enter a string: ")
result_string = input_string.replace('i', '')
print("String after removing 'i':", result_string)
Output
Enter a string: institute
String after removing 'i': nsttute
PrevNext