Strings

This page contains the CBSE Computer Science with Python class 11 Unit-4 chapter 1 Strings. You can find the solutions for chapter 1 of CBSE class 11 Computer Science with Python Exercise. So is the case if you are looking for CBSE class 11 Computer Science with Python related topic Strings questions and answers for the Exercise.
Question 1
1. Input a string “Green Revolution”. Write a script to print the string in reverse.
Answer 1
This program prints the given string in reverse order, that is, from the last character to the first character. In Python, this can be done easily by using string slicing with a step value of -1.
# Program to print a string in reverse

s = "Green Revolution"
print s[::-1]
Output
noituloveR neerG
Explanation
s[::-1] means:
start from the end of the string
move backward
take one character at a time
So, the entire string is printed in reverse. This is a simple and efficient way to reverse a string.
Question 2
2. Input the string “Success”. Write a script to check if the string is a palindrome or not.
Answer 2
A palindrome is a word or string that reads the same from left to right and from right to left. To check this, the string can be compared with its reversed form.
# Program to check palindrome

s = "Success"

if s == s[::-1]:
    print "Palindrome"
else:
    print "Not a palindrome"
Output
Not a palindrome
Explanation
s[::-1] gives the reverse of the string
If the original string and reversed string are the same, it is a palindrome
Otherwise, it is not a palindrome
Since "Success" is not the same when reversed, the string is not a palindrome.
Question 3
3. Input the string “Successor”. Write a script to split the string at every occurrence of the letter s.
Answer 3
The split() function is used to break a string into parts wherever the given separator occurs. Here, the separator is the letter 's'.
# Program to split the string at every 's'

s = "Successor"
print s.split('s')
Output
['Succe', '', 'or']
Explanation
The string is split wherever lowercase 's' appears
In "Successor", there are two consecutive 's' letters
Because of the consecutive separators, an empty string '' appears between them
Thus, split() breaks the string into a list of parts.
Question 4
4. Input the string “Successor”. Write a script to partition the string at the occurrence of the letter s. Also explain the difference between the function split() and partition().
Answer 4
The partition() function divides a string into three parts at the first occurrence of the given separator.
# Program to partition the string at first occurrence of 's'

s = "Successor"
print s.partition('s')
Output
('Succe', 's', 'sor')
Explanation
The result has three parts:
1.
the part before the separator
2.
the separator itself
3.
the part after the separator
So:
before s"Succe"
separator → "s"
after s"sor"
Difference between split() and partition()
Basis
split()
partition()
Working
Splits the string at all occurrences of the separator
Splits the string at the first occurrence only
Result type
Returns a list
Returns a tuple
Separator in result
Separator is not included
Separator is included in the result
Number of parts
Can return many parts
Always returns exactly three parts
Thus, split() is used when many parts are needed, while partition() is used when the string is to be divided into exactly three parts around the first separator.
Question 5
5. Write a program to print the pyramid.
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
Answer 5
The required pattern is:
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
This pattern can be printed by using nested loops.
# Program to print the number pyramid

for i in range(1, 6):
    for j in range(i):
        print i,
    print
Explanation
The outer loop controls the row number
The inner loop prints the same number again and again in that row
print i, prints the value on the same line
print alone moves to the next line
So:
first row prints 1 one time
second row prints 2 two times
third row prints 3 three times, and so on
Thus, the required pyramid is formed.
Question 6
6. What will be the output of the following statement? Also justify your answer.
>>> print 'I like Gita\'s pink colour dress'.
Answer 6
print 'I like Gita\'s pink colour dress'.
Output
I like Gita's pink colour dress
Explanation
The apostrophe in Gita’s is written inside a single-quoted string. Normally, a single quote would end the string, but here a backslash (\) is used before it.
\' is an escape sequence
it tells Python to treat the apostrophe as part of the string, not as the end of the string
Therefore, the statement is printed correctly without any error.
Question 7
7. Give the output of the following statements.
>>> str='Honesty is the best policy'
>>> str.replace('o','*')
Answer 7
str = 'Honesty is the best policy'
str.replace('o', '*')
Output
'H*nesty is the best p*licy'
Explanation
The replace() function returns a new string in which all occurrences of the given character are replaced.
Here:
every lowercase 'o' is replaced by '*'
So:
Honesty becomes H*nesty
policy becomes p*licy
The original string does not change automatically, because strings are immutable. Only the returned result shows the changed value.
Question 8
8. Give the output of the following statements.
>>> str='Hello World'
>>> str.istiltle()
Answer 8
str = "Hello World"
str.istitle()
Output
True
Explanation
The istitle() function checks whether the string is in title case.
A string is in title case when:
each word starts with a capital letter
the remaining letters in each word are lowercase
In "Hello World":
Hello starts with H
World starts with W
the remaining letters are lowercase
Therefore, the result is True.
Question 9
9. Give the output of the following statements.
>>> str="Group Discussion"
>>> print str.lstrip("Gro")
Answer 9
str = "Group Discussion"
print str.lstrip("Gro")
Output
up Discussion
Explanation
The lstrip("Gro") function removes characters from the left side of the string as long as they belong to the given set of characters.
The set here is:
G
r
o
Starting from the left of "Group Discussion":
G is removed
r is removed
o is removed
the next character is u, which is not in the given set
So the removal stops there, and the remaining string is:
up Discussion
This is why the output is up Discussion.
Question 10
10. Write a program to print alternate characters in a string. Input a string of your own choice.
Answer 10
This program prints every second character from the string. This can be done by using slicing with a step value of 2.
# Program to print alternate characters

s = raw_input("Enter a string: ")
print s[::2]
Sample Input
Computer
Output
Cmue
Explanation
[::2] means:
start from the beginning
move forward
take every second character
For "Computer":
C
m
u
e
are selected.
Thus, the program prints alternate characters of the string.
Question 11
11. Input a string “Python”. Write a program to print all the letters except the letter”y”.
Answer 11
This program prints each character of the string one by one, but skips the letter 'y'.
# Program to print all letters except 'y'

s = "Python"

for ch in s:
    if ch != 'y':
        print ch,
Output
P t h o n
Explanation
The for loop goes through each character in the string
The if statement checks whether the character is not 'y'
If the character is not 'y', it is printed
If the character is 'y', it is skipped
Thus, all letters except 'y' are displayed.
Question 12
12. Consider the string str = "Global Warming". Write statements in Python to implement the following:
a)
To display the last four characters.
b)
To display the substring starting from index 4 and ending at index 8.
c)
To check whether string has alphanumeric characters or not.
d)
To trim the last four characters from the string.
e)
To trim the first four characters from the string.
f)
To display the starting index for the substring “Wa”.
g)
To change the case of the given string.
h)
To check if the string is in title case.
i)
To replace all occurrences of letter “a” in the string with “*”.
Answer 12
Consider the string:
str = "Global Warming"
a) To display the last four characters
print str[-4:]
Output
ming
Explanation
-4: means the slicing starts from the fourth character from the end and continues up to the end of the string.
b) To display the substring starting from index 4 and ending at index 8
print str[4:9]
Output
al Wa
Explanation
In slicing, the starting index is included, but the ending index is excluded. So characters from index 4 to 8 are printed.
c) To check whether the string has alphanumeric characters or not
print str.isalnum()
Output
False
Explanation
isalnum() returns True only if all characters are letters or digits. Since "Global Warming" contains a space, it is not fully alphanumeric.
d) To trim the last four characters from the string
print str[:-4]
Output
Global War
Explanation
:-4 means all characters from the beginning up to the position before the last four characters.
e) To trim the first four characters from the string
print str[4:]
Output
al Warming
Explanation
4: means start from index 4 and continue up to the end.
f) To display the starting index for the substring Wa
print str.find("Wa")
Output
7
Explanation
The find() function returns the starting position of the first occurrence of the given substring. The substring "Wa" begins at index 7.
g) To change the case of the given string
print str.swapcase()
Output
gLOBAL wARMING
Explanation
swapcase() changes:
uppercase letters to lowercase
lowercase letters to uppercase
So the case of every alphabet is reversed.
h) To check if the string is in title case
print str.istitle()
Output
True
Explanation
Both words begin with capital letters:
Global
Warming
and the remaining letters are lowercase. Therefore, the string is in title case.
i) To replace all the occurrences of letter a with *
print str.replace('a', '*')
Output
Glob*l W*rming
Explanation
Every lowercase 'a' is replaced by '*'. So both occurrences of a in the string change accordingly.
Question 13
13. Study the given script:
def metasearch():
import re
p = re.compile('sing+')
search1 = re.search(p, 'Some singers sing well')
if search1:
match = search1.group()
index = search1.start()
lindex = search1.end()
print "matched", match, "at index", index, "ending at", lindex
else:
print "No match found"
What will be the output of the above script if search() from the re module is replaced by match() of the re module? Justify your answer.
Answer 13
Answer
No match found
Explanation
The difference between search() and match() is:
search() looks for the pattern anywhere in the string
match() checks only at the beginning of the string
If the pattern is 'sing+', then match() will look only at the start of the given string. Since the string does not begin with "sing", there is no match.
Therefore, the output is:
No match found
Question 14
14. What will be the output of the script mentioned below? Justify your answer.
def find():
import re
p = re.compile('sing+')
search1 = p.findall('Some singer sing well')
print search1
Answer 14
Given pattern:
p = re.compile('sing+')
search1 = p.findall('Some singer sing well')
print search1
Output
['sing', 'sing']
Explanation
The pattern 'sing+' means:
sin
followed by one or more g
So it matches:
"sing" inside "singer"
"sing" inside "sing well"
The findall() function returns all matching substrings in a list. Since the pattern appears twice, the list contains two items.
Thus, the output is:
['sing', 'sing']
Question 15
15. Rectify the error (if any) in the given statements.
>>> str="Hello Worl d"
>>> str[5]='p'
Answer 15
str = "Hello Worl d"
str[5] = 'p'
This gives an error because strings are immutable in Python. That means we cannot change a single character directly by using indexing.
So, the statement:
str[5] = 'p'
is incorrect.
Correct way
A new string should be created by using slicing and concatenation.
str = "Hello Worl d"
str = str[:5] + 'p' + str[6:]
print str
Output
HellopWorl d
Explanation
str[:5] takes the first five characters
'p' is added in place of the character at index 5
str[6:] takes the remaining part of the string
These parts are joined to form a new string, which is the correct way to modify string content.