Loading...
Please wait while we prepare your content
Please wait while we prepare your content
Solutions for Computer Science, Class 11, CBSE
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.
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.
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.
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.
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.
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.
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.
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.
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.
'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.
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.
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.
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.
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.
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.
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.
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.
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'.
["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'].
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'.
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".
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']
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.
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!".
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")
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() )
(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.
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)
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 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'
for
loop iterates over each index i
from 0
to ln-1
(i.e., 0
to 9
).Conditions within the loop:
Text[i].isupper()
: Checks if the character at index i
in the string Text
is an uppercase letter.
Text[i].lower()
and appends it to nText
.elif Text[i].isalpha()
: Checks if the character at index i
in the string Text
is an alphabetic letter (either uppercase or lowercase).
Text[i].upper()
and appends it to nText
.else
statement of loop:
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)
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:
else
statement appends 'A'
to nText
.nText = "mINDwORK" + "A" = "mINDwORKA"
4. Print Output:
print(nText)
outputs "mINDwORKA"
.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
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
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.
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.