Very Short Answer type Questions [1 mark each]
Question 1:
Explain capitalize( ) method in Python.
Answer:
The method capitalize( ) returns a copy of the string with only its first character capitalized.
Question 2:
Write the syntax for capitalize( ) method.
Answer:
Following is the syntax for capitalize( ) method : str.capitalize( )
Question 3:
What value will be returned by center (width, fillchar) method in Python.
Answer:
The method center( ) returns centered in a string of length width. Padding is done using the specified fillchar.
Question 4:
What are the two parameters of center( ) method.
Answer:
width — This is the total width of the string,
fillchar — This is the filler character
Question 5:
Describe the count(str, beg=0,end= len(string))
Answer:
The method count( ) returns the number of occurrences of substring sub in the range [start, end].
Question 6:
Describe the decode (encoding=’UTF8′, errors=’ strict’ )
Answer:
The method decode( ) decodes the string using the codec registered for encoding.
Question 7:
What do you n .an by encode(encoding= ‘UTF- 8,errors=’strict’)
Answer:
The method encode( ) returns an encoded version of the string. Default encoding is the current default string encoding.
Question 8:
What do you mean by endswith(suffix, beg=0, end=len(string))
Answer:
The method endswith( ) returns True if the string ends with the specified suffix, otherwise return False
Question 9:
Write the the syntax for find( ) method
Answer:
Following is the syntax for find( ) method :
str.find(str, beg=0 end=len(string))
Question 10:
Write the output of the following code.
# !/usr/bin/py thon
str1 = “this is string example… ,wow!!!”;\
str2 = “exam”;
print strl.find(str2);
print strl.find(str2,10);
print strl.find(str2, 40);
Answer:
15 15 -1
Question 11:
Write the syntax for isalnum( ) method.
Answer:
Following is the syntax for isalnum( )
method :
str.isalnum( )
Question 12:
Write the output of the following code.
# !/usr/bin/python
str = “this2009”; # No space in this string print str.isalnum( );
str = “this is string example….wow!!!”;
print str.isalnum( );
Answer:
True False
https://googleads.g.doubleclick.net/pagead/ads?client=ca-pub-7398766921532682&output=html&h=280&adk=2523109437&adf=568131091&pi=t.aa~a.1381849204~i.27~rp.4&w=750&fwrn=4&fwrnh=100&lmt=1668321352&num_ads=1&rafmt=1&armr=3&sem=mc&pwprc=6908628465&ad_type=text_image&format=750×280&url=https%3A%2F%2Fwww.cbsetuts.com%2Fncert-solutions-class-11-computer-science-python-strings%2F&fwr=0&pra=3&rh=188&rw=750&rpe=1&resp_fmts=3&wgl=1&fa=27&adsid=ChEIgM3knQYQi7aKz6raxcqeARI5AN8-ETKxdRu8noyUBdpNiYwq4zsCT9SLEqnLKpy-Sb83QRIUgTK7wcEpDrRhseGcc1X8ya7_gan4&uach=WyJXaW5kb3dzIiwiNi4wLjAiLCJ4ODYiLCIiLCIxMDguMC41MzU5LjEyNSIsW10sZmFsc2UsbnVsbCwiNjQiLFtbIk5vdD9BX0JyYW5kIiwiOC4wLjAuMCJdLFsiQ2hyb21pdW0iLCIxMDguMC41MzU5LjEyNSJdLFsiR29vZ2xlIENocm9tZSIsIjEwOC4wLjUzNTkuMTI1Il1dLGZhbHNlXQ..&dt=1673106819685&bpp=3&bdt=3746&idt=3&shv=r20230104&mjsv=m202301040101&ptt=9&saldr=aa&abxe=1&cookie=ID%3Dabbbd049660c1ef5-2201b28402d90024%3AT%3D1671719836%3ART%3D1671719836%3AS%3DALNI_MazhTIzYkzGHXl260j5g4NFTSeuqQ&gpic=UID%3D00000b960889abfa%3AT%3D1671719836%3ART%3D1673106818%3AS%3DALNI_MZitKfGKipH7BopsZPzcTHmvXnt4Q&prev_fmts=0x0%2C750x280%2C300x600%2C750x280%2C750x280%2C750x280%2C1519x754%2C728x90&nras=7&correlator=4356224157036&frm=20&pv=1&ga_vid=1762681568.1671719837&ga_sid=1673106819&ga_hid=1465708488&ga_fc=1&u_tz=330&u_his=16&u_h=864&u_w=1536&u_ah=824&u_aw=1536&u_cd=24&u_sd=1.25&dmc=4&adx=190&ady=2736&biw=1519&bih=754&scr_x=0&scr_y=0&eid=44759875%2C44759926%2C44759842%2C31071413%2C44779794&oid=2&pvsid=145708464233543&tmod=169065013&uas=0&nvt=1&ref=https%3A%2F%2Fwww.google.com%2F&eae=0&fc=1408&brdim=0%2C0%2C0%2C0%2C1536%2C0%2C1536%2C824%2C1536%2C754&vis=1&rsz=%7C%7Cs%7C&abl=NS&fu=128&bc=31&ifi=8&uci=a!8&btvi=6&fsb=1&xpc=Bz7YHvBUg5&p=https%3A//www.cbsetuts.com&dtd=729
Question 13:
Write the syntax for isalpha( ) method.
Answer:
Following is the syntax for isalpha( ) method :
str.isalpha( )
Question 14:
Write the output of the following code.
# !/usr/bin/python
str = “this”; # No space & digit in this string print str.isalpha( );
str = “this is string example….wow!!!”; print str.isalpha( );
Answer:
True False
Question 15:
Describe the isdigit( ) method
Answer:
The method isdigit( ) checks whether the string consists of digits only
Question 16:
Why we use islower( ) method in python?
Answer:
The method islower( ) checks whether all the case-based characters (letters) of the string are lowercase
Question 17:
Describe the isspace( ) method
Answer:
The method isspace( ) checks whether the string consists of whitespace.
Question 18:
Write the output of the following code.
#!/usr/bin/python
str = ” “;
print str.isspace( );
str = “This is string example….wow!!!”;
print str.isspace( );
Answer:
True
False
Question 19:
Write the output of the following code.
#!/usr/bin/python
str = “this is string example….wow!!!”;
print str.ljust(50, ‘0’);
Answer:
This is string example
…wow!!!000000000000000000
Question 20:
Write the output of the following code.
# !/usr/bin/python
str = “Waltons Technology….wow!!!”;
print “str.upper() : “str.upper()
Answer:
str.upper() : Waltons Technology ….WOW!!!
Question 21:
Rectify the error (if any) in the given statements.
>>>str = “Hello World”
>>>str[5] = ‘p’
Answer:
Strings are immutable. So convert to 2.
list > > >s = list (str)’p’)
>>s [5]=’p’
Question 22:
Give the output of the following state-ments :
>>>str = ‘Honesty is the best policy”
>>>str.replace (‘o’.’*’)
Answer:
H*nesty is the best p*licy.
Short Answer type Questions [2 mark each]
Question 1:
What do you mean by string in Python ?
Answer:
Strings are amongst the most popular types in Python. We can create them simply by characters in quotes. Python treats single quotes the same as double quotes.
Creating strings is as simple as assigning a value to a variable. For example :
var1 = ‘Waltons Technology!’
var2 = “Python Programming”
Question 2:
What is indexing in context to Python strings ? J Why is it also called two-way indexing ?
Answer:
In Python strings, each individual character is ! given a location number, called “index” and this process is called “indexing”. Python allocates indices in two directions :
- in forward direction, the indexes are numbered as 0,1, 2, length-1.
- in backward direction, the indexes are numbered as -1, -2, -3,…. length.
This is known as “two-way indexing”.
Question 3:
What is a string slice ? How is it useful ?
Answer:
A sub-part or a slice of a string, say s, can be obtained using s[n : m] where n and m are integers. Python returns all the characters at indices n, n+1, n+2,…. m-1.
For example,
‘Oswaal Books’ [1 : 4] will give ‘swa’
Question 4:
How you can “update” an existing string ?
Answer:
You can “update” an existing string by (re) assigning a variable to another string.
The new value can be related to its previous value or to a completely different string altogether.
Following is a simple example :
# !/usr/bin/python
var1 = ‘Hello World!’
print”Updated String:-“,var i[:6] + ‘Python’
Question 5:
Describe Triple Quotes in Python.
Answer:
Python’s triple quotes comes to the rescue by allowing strings to span multiple lines, including verbatim NEWLINEs, TABs, and any other special characters. The syntax for triple quotes consists of three consecutive single or double quotes.
# !/usr/bin/py thon
para str = “””this is a long string that is made up of several lines and non-printable characters such as
TAB ( \t ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like this within the brackets [ \n ], or just a NEWLINE within the variable assignment will also show up.
” ” ”
print para_str;
Question 6:
Define raw string with example.
Answer:
Raw strings don’t treat the backslash as a special character at all. Every character you put into a raw string stays in the way you wrote it :
# !/usr/bin/python
print ‘C:\\nowhere’
When the above code is executed, it produces the following result :
C:\nowhere
Now let’s make use of raw string. We would put expression in r’expression’ as follows :
# !/usr/bin/python
print r’C:\\nowhere’
When the above code is executed, it produces the following result :
C:\\nowhere
Question 7:
Explain Unicode String with example.
Answer:
Normal strings in Python are stored internally as 8-bit ASCII, while Unicode strings are stored as 16- bit Unicode. This allows for a more varied set of characters, including special characters from most languages in the world.
Example…….
#!/usr/bin/python
print u’Hello, world!’
Question 8:
Describe isdecimal( ) with example.
Answer:
The method isdecimal( ) checks whether the string consists of only decimal characters. This method is present only on Unicode objects.
Note : To define a string as Unicode, one simply prefixes a ‘u’ to the opening quotation mark of the assignment.
Below is the example.
Syntax :
Following is the syntax for isdecimal( ) method :
str.isdecimal( )
Question 9:
Explain zfill (width) with Syntax and Return Value
Answer:
The method zfill( ) pads string on the left with zeros to fill width.
Syntax : str.zfill(width)
Parameters: This is final width of the string. This is the width which we would get after filling zeros. Return Value: This method returns padded string
Question 10:
Write the output of the following code
# !/usr/bin/python
str = “this is string example….wow!!!”;
print str.zfill(40);
print str.zfill(50);
Answer:
On compiling and running the above program, this will produce the following result :
OOOOOOOOthis is string example….wow!!! 000000000000000000this is string example…. wow!!!
Question 11:
Write the output of the following code
# !/usr/bin/python
from string import maketrAns. # Required to call maketrAns. function.
intab = “aeiou” outtab = “12345”
trantab = maketrAns.(intab, outtab) str = “this is string example….wow!!!”; print str.trAns.late(trantab, ‘xm’);
Answer:
The given code will produce following result :
th3s 3s str3ng 21pl2….w4w!M
Question 12:
Describe the following method trans.late(table, deletechars=””)
Answer:
The method translate( ) returns a copy of the string in which all characters have been translated using table (constructed with the maketrans( ) function in the string module), optionally deleting all characters found in the string deletechars.
Question 13:
Give an example of title( ) in Python
Answer:
The following example shows the usage of title( ) method
# !/usr/bin/python
str = “this is string example….wow!!!”;
print str.title( );
On compile and run the above program, this will produce the following result :
This Is String Example….Wow!!!
Question 14:
Give an example of swapcase( ) in Python
Answer:
The following example shows the usage of swapcase( ) method.
# !/usr/bin/py thon
str = “this is string example….wow!!!”;
print str.swapcase( );
str = “THIS IS STRING EXAMPLE….WOW!!!”;
print str.swapcase( );
This will produce the following result :
THIS IS STRING EXAMPLE….WOW!!!
this is string example….wow!!!
Question 15:
Define strip ([chars]) with its syntax
Answer:
The method strip( ) returns a copy of the string in which all chars have been stripped from the beginning and the end of the string (default whitespace characters).
Syntax: str.strip([chars]);
Question 16:
Explain Parameters of str.startswith(str, beg=0,end=len( string) );
Answer:
str — This is the string to be checked.
beg — This is the optional parameter to set start index of the matching boundary.
end — This is the optional parameter to set end index of the matching boundary.
Question 17:
Explain Parameters of str.rjust(width[, fillchar])
Answer:
width — This is the string length in total after padding.
fillchar — This is the filler character, default is a space.
Question 18:
Write the output of the given Python code # !/usr/bin/python
str = “this is really a string example…. wow!!!”;
str = “is”;
print str.rfind(str);
print str.rfind(str, 0,10);
print str.rfind(str, 10, 0);
print str.find(str);
print str.find(str, 0,10);
print str.find(str, 10, 0);
Answer:
Above code will produce the following result :
5
5
-1
2
2
-1
Question 19:
Write the output of the given code #!/usr/bin/python
str = “this-is-real-string-example….wow!!!”;
print “Min character: ” + min(str);
str = “this-is-a-string-example….wow!!!”;
print “Min character: ” + min(str);
Answer:
Min character: !
Min character: !
Question 20:
Write the output of the given code #!/usr/bin/python
str = “this is really a string example….wow!!!”;
print “Max character: ” + max(str);
str = “this is a string example….wow!!!”;
print “Max character: ” + max(str);
Answer:
Output
Max character: y
Max character: x
Question 21:
Describe the function maketrans( )
Answer:
The method maketrans( ) returns a translation table that maps each character in the intab string into the character at the same position in the outtab string. Then this table is passed to the translate( ) function.
Syntax : str.maketrans(intab, outtab]);
Question 22:
Write the output of the following code
#!/usr/bin/py thon
str = ” this is string example….wow!!! “; print str.lstrip( );
str = “88888888this is string example….wow!!!8888888”;
print str.lstrip(‘8’);
Answer:
Output
this is string example….wow!!!
this is string example..,.wow!!!8888888
Question 23:
Study the given script
defmetasearch( ):
import re
p=re.compile(‘sing+’)
searchl=re.search(p,’ Some singers sing well’)
if searchl:
match=searchl.group( )
index=searchl.start( )
lindex=search 1 ,end( )
print “matched”, match, “at index”, index ,”ending at”, lindex
else:
print “No match found”
metasearch( )
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:
The output would be “N match found”
Justification : re.search( ) rill attempt the pattern throughout the string, i ntil it finds a match. re.match( ) on the other hand, only attempts the pattern at the very start of the string.
Example :
>>>re.match(“d”, “abcdef’) # No match
>>>re.search(“d”, “abcdef’) # Match
Question 24:
What will be the output of the script mentioned below? Justify your answer, def find) ):
import re
p=re.compile(‘ sing+’)
searchl=p.findall(‘Some singer sing well’)
print searchl
Answer:
Output : [‘sing’, ‘sing’]
Justification : fmdall( ) finds all occurences of the given substring with metacharacter.
Long Answer type Questions [4 mark each]
Question 1:
What is the concept of immutable strings ?
Answer:
Strings are immutable means that the contents of string cannot be chrnged after it is created.
For example :
>>> str = ‘Meney’
>>> str [3] = ‘h’
Type Error : ‘str’ object not support item assignment Python does not allow to change a character in a string. So an attempt to replace ‘e’ in the string by ‘h’ displays a Type Error.
Question 2:
What do you understand by traversing a string ? Ans. Traversing a string means accessing all the elements of the string one after the other by using the subscript. A string can be traversed using for loop or while loop.
For example :
A = ‘Python’
i = 0
while i < lenn (A) :
print A[i]
i = i + 1
Output :
P
y
t
h
o
n
Question 3:
Write a program to check whether the string is a palindrome or not.
Answer:
def palindrom ( ) :
str = input (“Enter the string”)
l = len (str)
P = l – 1
inex = 0
while (index < p) :
if (str[index] = = str [p]):
index = index + 1
p = p-1
else :
print “String is not a palindrom” break
else :
print “String is a palindrom”
Question 4:
Write a program to count number of ‘s’ in the string ‘successor’.
Answer:
def letcount ( ) :
word = ‘successor’
count = 0
for letter in word :
if letter = = ‘s’ :
count = count + 1
print (count)
Question 5:
Write a program to determine if the given word is present in the string.
Answer:
def wsearch ( ) :
imprt re
word = ‘good’
search1 = re.search (word, ‘I am a good person’)
if search1 :
position = search1.start ( )
print “matched”, word, “at position”, position
else :
print “No match found”
Question 6:
Input a string “Green Revolution”. Write a script to print the string in reverse.
Answer:
def reverseorder(list 1) :
relist = [ ]
i = len (list 1) -1
while i > = 0 :
relist.append (list [i])
i = 1 -1
return relist
Question 7:
Write a program to print the pyramid ?
Answer:
num = eval (raw_input (“Enter an integer from 1 to 5:”))
if num < 6 :
for i in range (1, num + 1):
for j in range (num-i, 0,-1):
print (” “)
for j in range (i, 0, -1):
print (j)
for j in range (2, i+1):
print (j)
print (” “)
else :
print (“The number entered is greater than 5”)
Output :
Question 8:
Write the syntax of isdecimal( ) and give suitable example
Answer:
The method isdecimal( ) checks whether the string consists of only decimal characters.
This method are present only on Unicode objects. Below is the example.
Syntax
str.isdecimal( )
Example
# !/usr/bin/python
str = u”this2009″;
print str.isdecimal( );
str = u”23443434″;
print str.isdecimal( );
This will produce the following result :
False
True
Question 9:
Write the output of the following python code #!/usr/bin/python
str = “Line1-a b c d e f\nLine2- a b
c\n\nLine4- a b c d”;
print str.splitlines( );
print str.splitlines(O);
print str.splitlines(3);
print str.splitlines(4);
print str.splitlines(5);
Answer:
Output
[‘Linel-a b c d e f’, ‘Line2- a b c’, “, ‘Line4- abed’]
[‘Linel-a b c d e f’, ‘Line2- a b c’, “, ‘Line4- abed’]
[‘Linel-a b c d e f\ri, ‘Line2- a b c\ri, ‘\n’, ‘Line4- a b c d’]
[‘Linel-a b c d e f\n’, ‘Line2- a b c\ri, ‘\ri, ‘Line4- a b c d’]
[‘Linel-a b c d e f\ri, ‘Line2- a b c\ri, ‘\n’, ‘Line4- a bed’]
Question 10:
Define split( ) with suitable example.
Answer:
The method split( ) returns a list of all the words in the string, using str as the separator (splits on all whitespace if left unspecified), optionally limiting the number of splits to num.
Syntax
str.split(str=””, num=string.count(str)).
Parameters
str — This is any delimeter, by default it is space.
num — This is number of lines to be made.
Example
# !/usr/bin/python
str = “Linel-abcdef \nLine2-abc \nLine4-abcd”;
print str.split( ); print str.split(‘ 1 );
OUTPUT
[‘Linel-abcdef’, ‘Line2-abc’, ‘Line4-abcd’]
[‘Linel-abcdef’, ‘\nLine2-abc \nLine4-abcd’]
Question 11:
Explain replace(old, new [, max])
Answer:
The method replace( ) returns a copy of the string in which the occurrences of old have been replaced with new, optionally restricting the number of replacements to max.
Syntax
str.replace(old, new[, max])
Parameters –
old — This is old substring to be replaced.
new — This is new substring, which would replace old substring.
max — If this optional argument max is given, only the first count occurrences are
replaced.
Example
# !/usr/bin/python
str = “this is string example….wow!!! this is really string”;
print str.replace(“is”, “was”); print str.replace(“is”, “was”, 3);
OUTPUT
thwas was string example….wow!!! thwas was really string
thwas was string example….wow!!! thwas is really string
Question 12:
Describe index(str, beg=0, end=len(string)) with example
Answer:
The method index( ) determines if string str occurs in string or in a substring of string if starting indexbeg and ending index end are given. This method is same as find( ), but raises an exception if
sub is not found.
Syntax
str.index(str, beg=0 end=len(string))
Example
# !/usr/bin/python
str = “this is string example….wow!!!”;
str = “exam”;
print str.index(str);
print str.index(str, 10);
print str.index(str, 40);
OUTPUT
15
15
Traceback (most recent call last):
File “test.py”, line 8, in
print str.index(str, 40);
ValueError: substring not found
shell returned 1
Discover more from EduGrown School
Subscribe to get the latest posts sent to your email.