Explore topic-wise InterviewSolutions in .

This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.

1.

Write the output of the following code# !/usr/bin/pythonstr = “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!!!

2.

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: !

3.

Write the output of the following code.# !/usr/bin/pythonstr = “this”; # No space & digit in this string print str.isalpha( );str = “this is string example….wow!!!”; print str.isalpha( );

Answer»

The following code is-

True False

4.

Describe the isdigit( ) method

Answer» The method isdigit( ) checks whether the string consists of digits only
5.

Write the output of the given code #!/usr/bin/pythonstr = “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 

6.

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;
7.

Write the output of the following python code #!/usr/bin/pythonstr = “Line1-a b c d e f\nLine2- a bc\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’]

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( )
9.

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]);

10.

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

11.

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’]

12.

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.

13.

Write a program that reads a string and then prints a string that capitalizes every other letter in the string.

Answer»

string = raw_input (“Enter a string:”) 

length = len (string) 

string2 = ” ”

for a in range (0, length, 2): 

string 2 + – string [a]

if a < (length-1): 

string 2+ = string [a+1],upper() 

print “Original string is”, string 

print “Converted string is”, string2

14.

Write a program that reads email id of a person in the form of a string and ensures that it belongs to domain @gmail.com. 

Answer»

email = raw_input (“Enter email ID :”) 

domain = “@gmail.com” 

lendo = len(domain) 

lenm = len(email) 

sub = email [lenm – lendo:]

if sub = = domain : 

if lendo ! = lenm : 

print “It is a valid email ID” 

else :

print “It is an invalid email ID” 

else : 

print “It’s domain is different”

15.

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”

16.

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” 

17.

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)

18.

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

19.

Write Python script that takes a string with multiple words and then capitalizes the first letter of each word and forms a new string out of it. 

Answer»

string = raw_input (“Enter a string :”) 

length = len (string) 

a = 0 end – length

string 2 = ” # empty string 

while a < length 

if a == 0 

string 2 += string [0].upper() 

a += 1

elif (string [a] = = ‘ ‘ and string [a+1) !=”) : 

string 2 + = string [a] 

string 2 + = string [a+l].upper( ) 

a + = 2

else : 

string 2 + = string [a] 

a + = 1 

print “Original string :”, string 

print “Converted string :”, string2

20.

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

21.

Explain expandtabs(tabsize=8) with example

Answer»

The method expandtabs( ) returns a copy of the string in which tab characters ie. ‘\t’ have been expanded using spaces, optionally using the given tabsize (default 8).

Syntax

Following is the syntax for expandtabs( ) method : str.expandtabs(tabsize=8)

Example 

#!/usr/bin/python 

str = “this is\tstring example….wow!!!”;

print “Original string: ” + str; 

print “Defualt exapanded tab: ” +

str.expandtabs( ); 

print “Double exapanded tab: ” + str.

expandtabs(16);

OUTPUT 

Original string: this is string example….wow!!! Defualt exapanded tab: this is string example…. wow!!! 

Double exapanded tab: this is string example…. wow!!! 

22.

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» The following code is-

True False
23.

Write the syntax for isalnum( ) method.

Answer» Following is the syntax for isalnum( )

method :

str.isalnum( )
24.

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

25.

Write the syntax for capitalize( ) method.

Answer»

Following is the syntax for capitalize( ) method : str.capitalize( )

26.

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]);

27.

Write the the syntax for find( ) method

Answer»

Following is the syntax for find( ) method : str.find(str, beg=0 end=len(string))

28.

Write the syntax for isalpha( ) method

Answer»

Following is the syntax for isalpha( ) method : str.isalpha( )

29.

Why we use islower( ) method in python?

Answer»

The method islower( ) checks whether all the case-based characters (letters) of the string are lowercase

30.

Describe the isspace( ) method

Answer» The method isspace( ) checks whether the string consists of whitespace
31.

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

32.

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

33.

Write the output of the given Python code # !/usr/bin/pythonstr = “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 : 

-1 

-1

34.

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!!!

35.

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!!!

36.

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
37.

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 :

1. in forward direction, the indexes are numbered as 0,1, 2, length-1. 

2. in backward direction, the indexes are numbered as -1, -2, -3,…. length. This is known as “two-way indexing”.

38.

What do you understand by traversing a string ? 

Answer»

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

t

n

39.

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!’

40.

Explain capitalize( ) method in Python.

Answer» The method capitalize( ) returns a copy of the string with only its first character capitalized.
41.

Write the output of the following code.#!/usr/bin/python str = ” “;print str.isspace( );str = “This is string example….wow!!!”; print str.isspace( );

Answer»

The following code. is -

True 

False

42.

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
43.

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!!!
44.

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
45.

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.

46.

Study the given script defmetasearch( ): import rep=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

47.

Write a program that reads a string and display the longest substring of the given string having just the consonants

Answer»

string = raw_input (“Enter a string :”) 

length = len (string) 

max length = 0 

max sub = ‘ ‘ 

sub = ‘ ‘ lensub = 0

for a in range (length) : 

if string [a] in aeiou ‘or string [a] in’AEIOU’: 

if lensub > maxlength : 

maxsub = sub 

maxlength – lensub 

sub = ‘ ‘ lensub 0

else : 

sub += string[a]

 lensub = len(sub) 

a + = 1 

print “Maximum length consonent 

substring is :”, maxsub, 

print “with”, maxlength, “characters”

48.

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

49.

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» The code is-

15 15 -1
50.

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.