Python String MCQ : Set 3

Python String MCQ

1). What is the value of result after executing the given code?

str1 = “Sqa Tools Learning”
result = “”
vowels = [“a”,”e”,”i”,”o”,”u”,
“A”,”E”,”I”,”O”,”U”]

for char in str1:
    if char in vowels:
        result = result + char*3
    else:
        result = result + char*2
print(result)

a) Ssqqaa Ttoools Lleeaarrnniinngg
b) Sqa Tools Learning
c) SSqqaaa TToooooollss LLeeeaaarrnniiinngg
d) Sqa Tools Leaarrnniinngg

Correct answer is: c) SSqqaaa TToooooollss LLeeeaaarrnniiinngg
Explanation: The code iterates over each character in the string str1. If the character is a vowel, it appends the character three times to the result string. Otherwise, it appends the character twice to the result string. After executing the code, the result string will contain the modified string with repeated characters.

2). What is the output of the following code?

string = “Cricket Plays Virat”

List = string.split(” “)
List.reverse()
” “.join(List)

a) “Cricket Plays Virat”
b) “Virat Plays Cricket”
c) “Cricket Virat Plays”
d) “Plays Cricket Virat”

Correct answer is: b) “Virat Plays Cricket”
Explanation: The code snippet does not modify the variable string. It only performs operations on a list created from string.

3). What is the output of the following code?

string = “JAVA is the Best Programming Language in the Market”
List1 = string.split(” “)

for word in List1:
    if word == “JAVA”:
        index = List1.index(word)
        List1[index] = “PYTHON”
print(” “.join(List1))

a) “JAVA is the Best Programming Language in the Market”
b) “PYTHON is the Best Programming Language in the Market”
c) “PYTHON is the Best Programming Language in the Python”
d) “JAVA is the Best Programming Language in the Python”

Correct answer is: b) “PYTHON is the Best Programming Language in the Market”
Explanation: The code splits the string into a list of words using the space delimiter. It then iterates over the words and checks if each word is equal to “JAVA”. If it finds a match, it replaces that word with “PYTHON”. Finally, it joins the modified list of words back into a string and prints the result.

4). What is the output of the following code?

string = “Python efe language aakaa hellolleh”
List = string.split(” “)
new_list = []

for val in List:
    if val == val[::-1]:
        new_list.append(val)
print(new_list)

a) [‘efe’, ‘aakaa’, ‘hellolleh’]
b) [‘efe’, ‘hellolleh’]
c) [‘Python’, ‘language’]
d) []

Correct answer is: a) [‘efe’, ‘aakaa’, ‘hellolleh’]
Explanation: The code splits the string into a list of words using the space character as a delimiter. Then it checks each word in the list, and if a word is equal to its reverse (palindrome), it appends it to the new_list. Finally, it prints the new_list, which contains the palindrome words from the original string.

5). What will be the output of the following code?

list1 = [“There”, “are”, “Many”, “Programming”, “Language”]
” “.join(list1)

a) “ThereareManyProgrammingLanguage”
b) “There are Many Programming Language”
c) “There, are, Many, Programming, Language”
d) “Many Language Programming are There”

Correct answer is: b) “There are Many Programming Language”
Explanation: The join() method concatenates the elements of list1 with spaces in between them, resulting in the string “There are Many Programming Language”. The resulting string is then printed.

6). What is the purpose of the following code?

string = “im am learning python”
count = 0

for char in string:
    count += 1
print(“Length of the string using loop logic: “, count)

a) Count the number of occurrences of each character in the string.
b) Count the number of words in the string.
c) Calculate the sum of the ASCII values of all characters in the string.
d) Calculate the length of the string.

Correct answer is: d) Calculate the length of the string.
Explanation: The code iterates over each character in the string using a loop and increments a counter variable (count) by 1 for each character. After the loop completes, the value of count represents the length of the string.

7). What is the output of the following code?

string1=”Prog^ra*m#ming”
test_str = ”.join(letter for letter in string1 if letter.isalnum())
print(test_str)

a) Programming
b) Program#ming
c) Program#ming
d) Error

Correct answer is: a) Programming
Explanation: The code removes all non-alphanumeric characters from the string string1 using a generator expression. The join() function concatenates the remaining alphanumeric characters into a single string. The resulting string, which contains only alphabetic and numeric characters, is then printed.

8). What is the output of the following code?

string2 = “Py(th)#@&on Pro$*#gram”
test_str = “”.join(letter for letter in string2 if letter.isalnum())
print(test_str)

a) Python Program
b) Pythongram
c) PythnProgram
d) Pyth@onPro#gram

Correct answer is: a) Python Program
Explanation: The code removes all non-alphanumeric characters from the string `string2` using a generator expression and the `isalnum()` method. The resulting string is then assigned to the variable `test_str` and printed, which gives the output “Python Program”.

9). What is the purpose of the following code snippet?

string1 = “Very Good Morning, How are You”
string2 = “You are a Good student, keep it up”
List = []

for word in string1.split(” “):
    if word in string2.split(” “):
        List.append(word)
” “.join(List)

a) It counts the number of matching words between string1 and string2.
b) It concatenates the words that are common to both string1 and string2.
c) It converts the words from string1 and string2 into a list and joins them with a space.
d) It removes duplicate words from string1 and string2.

Correct answer is: b) It concatenates the words that are common to both string1 and string2.
Explanation: The code compares each word in string1 with each word in string2 and appends the common words to the List variable. Finally, it joins the words in List with a space, resulting in a string of the common words.

10). What will be the output of the code?

string = “Learning is a part of life and we strive”
print(“Longest words: “, max(string.split(” “), key=len))

a) Longest words: Learning
b) Longest words: striving
c) Longest words: Learning is
d) Longest words: part of life and

Correct answer is: a) Longest words: Learning
Explanation: The code splits the string into words and finds the longest word, which in this case is “Learning”. Therefore, the output will be “Longest words: Learning”.

11). What is the output of the following code?

string = “sqatoolssqatools”
string2 = string[::-1]

if string == string2:
    print(“Given string is a palindrome”)
else:
    print(“Given string is not a palindrome”)

a) Given string is a palindrome
b) Given string is not a palindrome
c) Error
d) None of the above

Correct answer is: a) Given string is a palindrome
Explanation: In this code, the string “sqatoolssqatools” is assigned to the variable string. The variable string2 is assigned the reverse of string using the slicing technique [::-1]. The condition if string == string2 checks if string is equal to its reverse. Since the reverse of “sqatoolssqatools” is the same as the original string, the condition is true and the code prints “Given string is a palindrome”.

12). What does the expression string.split(” “) do?

a) Splits the string at each space character.
b) Splits the string at each comma character.
c) Reverses the order of words in the string.
d) Joins the string with spaces.

Correct answer is: a) Splits the string at each space character.
Explanation: The split(” “) method is used to split the string into a list of substrings at each occurrence of a space character.

13). What is the output of the following code?

string = “sqatools python”
print(” “.join(string.split(” “)[::-1]))

a) “sqatools python”
b) “python sqatools”
c) “sqatoolspython”
d) Error

Correct answer is: b) “python sqatools”
Explanation: The code splits the string at each space using the split() method, creating a list of substrings. The [::-1] slice notation is used to reverse the order of the list. Finally, the join() method concatenates the reversed list of substrings with a space between them, resulting in “python sqatools”.

14). What is the output of the following code?

string = “sqatools”
dictionary = dict()

for char in string:
    dictionary[char] = string.count(char)
print(dictionary)

a) {‘s’: 1, ‘q’: 1, ‘a’: 1, ‘t’: 1, ‘o’: 2, ‘l’: 1}
b) {‘s’: 1, ‘q’: 1, ‘a’: 1, ‘t’: 1, ‘o’: 2, ‘l’: 1, ‘s’: 1}
c) {‘s’: 2, ‘q’: 1, ‘a’: 1, ‘t’: 1, ‘o’: 2, ‘l’: 1}
d) {‘s’: 1, ‘q’: 1, ‘a’: 1, ‘t’: 1, ‘o’: 1, ‘l’: 1}

Correct answer is: c) {‘s’: 2, ‘q’: 1, ‘a’: 1, ‘t’: 1, ‘o’: 2, ‘l’: 1}
Explanation: The code counts the number of occurrences of each character in the string and stores the counts in a dictionary. The resulting dictionary will have key-value pairs representing each unique character and its count in the string.

15). What is the output of the given code?

string = “sqatools”

for i in range(len(string)):
    if i%2 == 0:
        print(string[i], end = “”)

a) sato
b) saoo
c) saol
d) sqao

Correct answer is: c) saol
Explanation: The code iterates over the characters in the string and prints only the characters at even indices, which are ‘s’, ‘a’, ‘t’, and ‘l’.

16). What is the value of the variable count after executing the given code?

string = “python1”
count = 0

for char in string:
    if char.isnumeric():
        count += 1

a) 0
b) 1
c) 6
d) None of the above

Correct answer is: b) 1
Explanation: The code counts the number of numeric characters in the string. Since there is one numeric character ‘1’ in the string, the value of count becomes 1.

17). What will be the output of the code?

string = “I am learning python”
vowels = [“a”,”e”,”i”,”o”,”u”,”A”,”E”,”I”,”O”,”U”]
count=0

for char in string:
    if char in vowel:
        count+=1
print(“Number of vowels: “,count)

a) Number of vowels: 0
b) Number of vowels: 3
c) Number of vowels: 5
d) Number of vowels: 6

Correct answer is: d) Number of vowels: 6
Explanation: The code counts the number of vowels in the given string “I am learning python”.

18). What is the output of the following code?

string = “sqltools”
vowel = [“a”,”e”,”i”,”o”,”u”,”A”,”E”,”I”,”O”,”U”]
count = 0

for char in string:
    if char not in vowel:
        count += 1
print(“Number of consonants: “, count)

a) Number of consonants: 6
b) Number of consonants: 7
c) Number of consonants: 8
d) Number of consonants: 9

Correct answer is: a) Number of consonants: 6
Explanation: The code counts the number of characters in the string that are not in the vowel list, which represents the vowels. The string “sqltools” has six consonants (‘s’, ‘q’, ‘l’, ‘t’, ‘s’, ‘l’), so the output is “Number of consonants: 6”.

19). What is the output of the following code?

string = “sqatools”
from collections import OrderedDict
“”.join(OrderedDict.fromkeys(string))

a) “sqatools”
b) “sqatol”
c) “sqat”
d) “sqtols”

Correct answer is: b) “sqatol”
Explanation: The code removes duplicate characters from the string “sqatools” using an OrderedDict. The OrderedDict.fromkeys() method creates an OrderedDict with the unique characters from the string as keys. The “”.join() method is then used to concatenate these keys into a new string, resulting in “sqat”.

20). What will be printed as the output of the code?

string = “python$$#sqatools”
s='[@_!#$%^&*()<>?/\|}{~:]’
count=0

for char in string:
    if char in s:
        count+=1

if count > 0:
    print(“Given string has special characters”)
else:
    print(“‘Given string does not has special characters”)

a) Given string has special characters
b) Given string does not have special characters
c) Given string has 2 special characters
d) Given string does not have any special characters

Correct answer is: a) Given string has special characters
Explanation: Since the count variable is greater than 0, it indicates that the string has special characters, and thus, the corresponding message “Given string has special characters” will be printed as the output.

21). What is the output of the following code?
 
string1 = “I live in pune”
print(string1.upper())
 
a) I live in pune
b) i live IN PUNE
c) I LIVE IN PUNE
d) i live in pune
 
Correct answer is: c) I LIVE IN PUNE
Explanation: The upper() method converts all characters in the string to uppercase. In this case, it converts “i” to “I” and “pune” to “PUNE”.
 
22). What will be the output of the given code?
 
string1= “objectorientedprogramming\n”
print(string1.rstrip())
 
a) “objectorientedprogramming\n”
b) “objectorientedprogramming”
c) “objectorientedprogramming “
d) “objectorientedprogrammin”
 
Correct answer is: b) “objectorientedprogramming”
Explanation: The rstrip() method removes the newline character from the end of the string, resulting in the string “objectorientedprogramming”.
 
23). What is the value of the variable result after executing the given code?
 
a) “2.146”
b) “2.147”
c) “2.1470”
d) “2.14652”
 
Correct answer is: b) “2.147”
Explanation: The given code rounds the value of num to 3 decimal places and converts it to a string. The resulting value is then appended to the result variable. Therefore, the value of result will be “2.146” after executing the code.
 
24). What will be the output of the following code?
 
string = “five four three two one”
new_str = “”
 
for val in string.split():
    if val == “one”:
        new_str += “1”
    elif val == “two”:
        new_str += “2”
    elif val == “three”:
        new_str += “3”
    elif val == “four”:
        new_str += “4”
    elif val == “five”:
        new_str += “5”
    elif val == “six”:
        new_str += “6”
    elif val == “seven”:
        new_str += “7”
    elif val == “eight”:
        new_str += “8”
    elif val == “nine”:
        new_str += “9”
    elif val == “ten”:
        new_str += “10”
     
print(new_str)
 
a) “54321”
b) “543210”
c) “five four three two one”
d) “”
 
Correct answer is: a) “54321”
Explanation: The code iterates through each word in the string and replaces it with its corresponding numeric value. The resulting new_str will contain the concatenation of the numeric representations of the words in the original string, in the order they appear.
 
25). What is the output of the code?
 
string = “I am solving problems based on strings”
 
List = string.split(” “)
List.index(“problems”)
 
a) “problems”
b) 3
c) [“problems”]
d) Error
 
Correct answer is: b) 3
Explanation: The index() method is used to find the index of the first occurrence of the specified element in the list. In this case, “problems” is the element being searched, and its index in the list is 3.

Leave a Comment