String
String
Question 1
Question 2
Question 3
Question 4
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
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.
Question 1
Answer
True
Reason — An empty string is a string without any characters inside, having length zero.
Question 2
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
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
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
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
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
Answer
False
Reason — The ord() function is used to return the corresponding Unicode value of a character.
Question 9
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
Answer
False
Reason — Strings are immutable means that the content of the string cannot be changed after it is created.
Question 1
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
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
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?
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
Answer
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"?
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
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
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
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
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
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
print("ComputerScience".split("er", 2))
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
1. 87
2. 88
3. 89
4. 90
Answer
89
STR = "RGBCOLOR"
colors = list(STR)
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
[Link]("B") method removes the first occurrence of the value 'B'. Similarly,
[Link](2) removes and returns the item at index 2, which is 'B'.
Question 16
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".
Question 1
Answer
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
Reasoning (R): The capitalize() method returns a string where the first character is uppercase and the rest
is lower case.
Answer
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.
Answer
Question 4
Reasoning (R): In strings, the values are enclosed inside double or single quotes.
Answer
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.
Answer
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.
Answer
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
Reasoning (R): In forward and backward indexing, the indices start with 1st index.
Answer
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
Reasoning (R): isdigit() function checks for the presence of all the digits in an inputted string.
Answer
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 [Link]() will return False. On the other hand,
str2 contains only digits, so [Link]() will return True.
Solutions to Unsolved Questions
Question 1
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
Answer
The split() function breaks up a string at the specified separator and returns a list of substrings. The
syntax is [Link]([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([Link](";"))
Output
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
>>> 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)
Answer
Output
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 [Link](substring) != -1 evaluates to True, and
the code prints "Python found the substring!".
Question 5(b)
s = "Strings in Python"
print([Link]())
print([Link]())
s6 = [Link]("in", "data type")
print(s6)
Answer
Output
Strings in python
Strings In Python
Strdata typegs data type Python
Explanation
The [Link]() method capitalizes the first letter of the string and converts the rest to lowercase,
resulting in "Strings in python". The [Link]() method capitalizes the first letter of each word, producing
"Strings In Python". The [Link]("in", "data type") method replaces occurrences of "in" with
"data type", giving "Strdata typegs data type Python" as output.
Question 6
Answer
Output
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
Answer
(ii) Scienc
(iv) e
(vi) eniSrtpo
(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'.
(vi) It slices the string mySubject with a step of -2, which reverses the string and selects every second
character.
(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 mySubjectstarts 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:
Answer
(a)
s = 'sequence'
index = [Link]('e', [Link]('e', [Link]('e') + 1) + 1)
print(index)
Output
(b)
s = 'FuNcTioN'
print([Link]())
Output
fUnCtIOn
(c)
s = 'School'
print('Z' in s)
Output
False
Question 9
(b) To replace all the occurrences of letter 'a' in the string with "*".
Answer
(a)
Output
ming
(b)
Output
Glob*l W*rming
Question 10
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
Initialization
Text = "Mind@Work!"
ln = len(Text)
nText = ""
● A for loop iterates over each index i from 0 to ln-1 (i.e., 0 to 9).
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.
● 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.
print(nText)
Step-by-Step Execution
1. Initial States:
● Text = "Mind@Work!"
● ln = 10
● nText = ""
2. Loop Iterations:
4. Print Output:
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([Link]('h'))
Output
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
Output
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
print(modified_sentence)
Output
Question 14
Write a script to partition the string 'INSTITUTE' at the occurrence of letter 'T'.
Solution
string = 'INSTITUTE'
parts = [Link]('T')
print(parts)
Output
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
Solution
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
Output
Question 18
Solution
Output