A string is a Sequence of characters.
Positive subscript helps in accessing the string from the beginning.
Negative subscript helps in accessing the string from the end.
'+' operator concatenates the strings on both sides of the operator.
The find() method returns the lowest index of the substring if it is found in the given string.
capitalize() function returns the exact copy of the string with the first letter in uppercase.
Strings cannot be modified as they are immutable data types.
The sequential accessing of each of the elements in a string is called string traversal.
in membership operator returns True if a character or substring exists in the given string.
String slice is a part of the string containing some contiguous characters from the string.
The find() function returns -1 when substring is not found in the main string.
count() function is used to count how many times an element has occurred in a list.
startswith() function returns True if the given string starts with the specified substring, else returns False.
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.
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.
"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".
Multiplication operator (*) replicates the string.
Answer
True
Reason — Multiplication operator (*) creates a new string by repeating multiple copies of the same string.
We can combine two strings with the help of '&' operator.
Answer
False
Reason — We can combine two strings with the help of '+' operator.
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.
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.
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.
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.
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.
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.
Which of the following is not a Python legal string operation?
- 'abc' + 'abc'
- 'abc' *3
- 'abc' + 3
- '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.
In Python string, + and * represent which of the following operations?
- Concatenation, Replication
- Addition, Multiplication
- Neither (i) nor (ii)
- 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.
Which of following is not a valid string operation?
- Slicing
- Concatenation
- Repetition
- Floor
Answer
Floor
Reason — In Python, valid string operations include slicing, concatenation, and repetition. However, "floor" is not a valid string operation.
How many times is the word "Python" printed in the following statement?
s = 'I love Python'
for ch in s[3:8]:
print('Python')
- 11 times
- 8 times
- 3 times
- 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.
Which of the following is the correct syntax of String Slicing?
- String_name [start : end]
- String_name [start : step]
- String_name [step : end]
- 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.
What is the correct Python code to display the last four characters of "Digital India"?
- str [-4 :]
- str [4 :]
- str [*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.
What will be the output of the following code?
str1= "I love Python."
strlen = len(str1)
print(strlen)
- 9
- 29
- 14
- 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.
What will be the output of the following code?
Str1= 'My name is Nandini '
Str2 = Str1[3:7]
strlen = len(Str2)
print(strlen)
- 4
- 14
- 24
- 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.
Which method removes all the trailing whitespaces from the right of the string?
- tolower()
- upper()
- Istrip()
- rstrip()
Answer
rstrip()
Reason — The rstrip()
function removes all the trailing whitespaces from the right of the string.
To concatenate means to ............... .
- replicate
- join
- split
- 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.
............... function will always return tuple of 3 elements.
- index()
- split()
- partition()
- 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.
What will be the output of the following code?
A = 'Virtual Reality'
A.replace('Virtual', 'Augmented')
- Virtual Augmented
- Reality Augmented
- Augmented Virtual
- 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'.
What will be the output of the following?
print("ComputerScience".split("er", 2))
- ["Computer", "Science"]
- ["Comput", "Science"]
- ["Comput", "erScience"]
- ["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'].
What is the ASCII equivalent decimal no. for 'Y'?
- 87
- 88
- 89
- 90
Answer
89
Reason — The ASCII equivalent decimal number for 'Y' is 89.
STR = "RGBCOLOR"
colors = list(STR)
How do we delete 'B' in given List colors?
- del colors[2]
- colors.remove("B")
- colors.pop(2)
- 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'.
Which of the following will give "Simon" as output?
str1 = "Hari,Simon,Vinod"
- print(str1[-7:-12])
- print(str1[-11:-7])
- print(str1[-11:-6])
- 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".
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.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- 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.
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.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- 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.
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.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- 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.
Assertion (A): In Python, the strings are mutable.
Reasoning (R): In strings, the values are enclosed inside double or single quotes.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- 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.
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.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- 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]
.
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.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- 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.
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.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- 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.
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.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- 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.
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)
abcabcabc
In the above example, the string "abc" is repeated 3 times to produce "abcabcabc".
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:
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.
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(";"))
['blue', 'red', 'green']
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.
Write the output of the following:
>>> x = "hello"
>>> print(x[1:-2])
Answer
el
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".
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
Python found the substring!
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!".
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
Strings in python
Strings In Python
Strdata typegs data type Python
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.
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
Substring, 'work', found at index: 0
Substring, 'har ' ,found at index: 5
Doesn't contain given substring
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".
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.
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)
7
(b)
s = 'FuNcTioN'
print(s.swapcase())
fUnCtIOn
(c)
s = 'School'
print('Z' in s)
False
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)
ming
(b)
str1 = "Global Warming"
replaced_str = str1.replace('a', '*')
print(replaced_str)
Glob*l W*rming
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
mINDwORKA
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 ofText
, which is10
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 indexi
from0
toln-1
(i.e.,0
to9
).
Conditions within the loop:
Text[i].isupper()
: Checks if the character at indexi
in the stringText
is an uppercase letter.- If true, it converts the character to lowercase using
Text[i].lower()
and appends it tonText
.
- If true, it converts the character to lowercase using
elif Text[i].isalpha()
: Checks if the character at indexi
in the stringText
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 tonText
.
- If the character is alphabetic but not uppercase, it converts the character to uppercase using
else
statement of loop:
- The
else
statement in this context is associated with thefor
loop, meaning it executes after the loop has completed iterating over all the indices. nText = nText + 'A'
appends the character'A'
to the end ofnText
.
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:
Index | Character | Condition | Transformation | nText |
---|---|---|---|---|
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'
tonText
. nText = "mINDwORK" + "A" = "mINDwORKA"
4. Print Output:
print(nText)
outputs"mINDwORKA"
.
Input the string 'My School'. Write a script to partition the string at the occurrence of letter 'h'.
s = "My School"
print(s.partition('h'))
('My Sc', 'h', 'ool')
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.)
s = input("Enter a string: ")
s1 = s.title()
print(s1)
Enter a string: python programming is fun
Python Programming Is Fun
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.
sentence = input("Enter a sentence: ")
modified_sentence = sentence.replace(' ', '-')
print(modified_sentence)
Enter a sentence: Innovation drives progress
Innovation-drives-progress
Write a script to partition the string 'INSTITUTE' at the occurrence of letter 'T'.
string = 'INSTITUTE'
parts = string.partition('T')
print(parts)
('INS', 'T', 'ITUTE')
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
mmin
y Py
My Python Program
My Python Programming
My Python
My
str[-5:-1]
extracts the substring from the 5th last character up to, but not including, the last character: "mmin".str[1:5]
extracts the substring from index 1 to 4: "y Py".str[:-4]
extracts the substring from the beginning up to, but not including, the last 4 characters.str[0:]
extracts the substring from index 0 to the end.str[:13-4]
is equivalent to str[:9], which extracts the substring from the beginning up to, but not including, index 9: "My Python".str[:3]
extracts the substring from the beginning up to, but not including, index 3: "My ".
Write a program to count the number of each vowel in a given string.
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)
Enter a string: The quick brown fox jumps over the lazy dog.
Vowel counts: {'a': 1, 'e': 3, 'i': 1, 'o': 4, 'u': 2}
Write a program that reads a line, then counts how many times the word 'is' appears in the line and displays the count.
line = input("Enter a line: ")
line = line.lower()
words = line.split()
count = words.count('is')
print("The word 'is' appears", count, "times.")
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.
Write a program to remove 'i' (if any) from a string.
input_string = input("Enter a string: ")
result_string = input_string.replace('i', '')
print("String after removing 'i':", result_string)
Enter a string: institute
String after removing 'i': nsttute