Python String MCQ : Set 4

Python String MCQ

1). What does the following code do?

string1 = “I want to eat fast food”
print(“Occurrences of food: “, string1.count(“food”))

a) It prints the number of occurrences of the word “food” in the string.
b) It counts the number of words in the string.
c) It checks if the word “food” is present in the string.
d) It replaces the word “food” with another word in the string.

Correct answer is: a) It prints the number of occurrences of the word “food” in the string.
Explanation: The count() method is used to count the number of occurrences of a substring in a string. In this case, it counts the number of occurrences of the word “food” and the result is printed.

2). What will be the output of the code snippet?

string = “We are learning python”

for word in string.split(” “):
    if len(word) > 3:
print(word, end=” “)

a) We are learning python
b) learning python
c) We are
d) are learning python

Correct answer is: b) learning python
Explanation: The code prints only the words from the given string that have a length greater than 3. In this case, “learning” and “python” are the only words that satisfy the condition, so they will be printed.

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

import re
string = “qwerty”

result = re.split(‘a|e|i|o|u’, string)
print(” “.join(result))

a) q w r t y
b) qw rty
c) qwerty
d) qwer ty

Correct answer is: b) qw rty
Explanation: The code splits the string at every occurrence of the vowels ‘a’, ‘e’, ‘i’, ‘o’, and ‘u’. The resulting substrings are stored in the result list. The join() method is used to concatenate the substrings with a space in between, resulting in “qw rty”.

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

string = “I’m learning python at Sqatools”
List = string.split(” “)

for i in range(len(List)):
    if List[i] == “python”:
        List[i] = “SQA”
    elif List[i] == “Sqatools”:
        List[i] = “TOOLS”
print(” “.join(List))

a) I’m learning python at Sqatools
b) I’m learning SQA at TOOLS
c) I’m learning SQA at Sqatools
d) I’m learning python at TOOLS

Correct answer is: b) I’m learning SQA at TOOLS
Explanation: The code splits the string into a list of words using the space delimiter. It then iterates over each word in the list. If the word is “python”, it replaces it with “SQA”. If the word is “Sqatools”, it replaces it with “TOOLS”. Finally, it joins the modified list of words back into a string with spaces. Therefore, the output will be “I’m learning SQA at TOOLS”.

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

string = “Sqatool python”
new_str = “”

for char in string:
    if char == “a”:
        new_str += “1”
    elif char == “t”:
        new_str += “2”
    elif char == “o”:
        new_str += “3”
    else:
        new_str += char
print(new_str)

a) Sq1t22l pyth3n
b) Sq1233l py2h3n
c) Sqatool pyth3n
d) Sqa2ool python

Correct answer is: b) Sq1233l py2h3n
Explanation: The code iterates over each character in the given string. If the character is ‘a’, it replaces it with ‘1’. If the character is ‘t’, it replaces it with ‘2’. If the character is ‘o’, it replaces it with ‘3’. Otherwise, it keeps the original character. The final value of new_str is “Sq1233l py2h3n”.

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

List1 = [“Python”, ” “, ” “, “sqatools”]
List2 = []

for string in List1:
    if string != ” “:
        List2.append(string)
print(List2)

a) [“Python”, “sqatools”]
b) [“Python”, “”, “sqatools”]
c) [“Python”, ” “, ” “, “sqatools”]
d) []

Correct answer is: a) [“Python”, “sqatools”]
Explanation: The code iterates over each element in List1. If the element is not equal to a single space ” “, it is appended to List2. The elements “Python” and “sqatools” are not equal to a space, so they are added to List2. The resulting list is [“Python”, “sqatools”].

7). What will be the value of string2 after executing the code snippet?

string1 = “Sqatools : is best, for python”
string2 = “”
punc = ”’!()-[]{};:'”\,<>./?@#$%^&*_~”’

for char in string1:
    if char not in punc:
        string2 += char

a) “Sqatools : is best, for python”
b) “Sqatools is best for python”
c) “Sqatools:isbestforpython”
d) “Sqatools : is best for python”

Correct answer is: b) “Sqatools is best for python”
Explanation: The code removes all punctuation characters from string1 and stores the modified string in string2. The punctuation characters in string1 are “:, “. Therefore, the resulting string will be “Sqatools is best for python” with no spaces after “:”.

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

string = “hello world”
list1 = []

for char in string:
    if string.count(char) > 1:
        list1.append(char)
print(set(list1))

a) {‘l’, ‘o’}
b) {‘e’, ‘l’, ‘o’, ‘r’}
c) {‘o’}
d) {‘l’}

Correct answer is: a) {‘l’, ‘o’}
Explanation: In the given string, both ‘l’ and ‘o’ appear more than once. Therefore, the set() function removes duplicates, resulting in the set of characters {‘l’, ‘o’} being printed.

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

string1 = “iamlearningpythonatsqatools”
string2 = “pystlmi”
string3 = set(string1)
count = 0

for char in string3:
    if char in string2:
        count += 1

if count == len(string2):
    print(True)
else:
    print(False)

a) True
b) False
c) Error
d) None

Correct answer is: a) True
Explanation: The code checks if all characters in string2 are present in string1. Since all characters in string2 are found in string1, the condition count == len(string2) evaluates to True, and therefore, the output is True.

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

string = “xyabkmp”
print(“”.join(sorted(string)))

a) “xyabkmp”
b) “mpkba”
c) “abkmpxy”
d) “pkmabxy”

Correct answer is: b) “abkmpxy”
Explanation: The code sorts the characters in the string alphabetically using the `sorted()` function and then joins the sorted characters together using the `””.join()` method. So, the output will be the string “abkmpxy” with the characters in alphabetical order.

11). What does the following code snippet do?

import random

result = ” “
for i in range(9):
    val = str(random.randint(0, 1))
    result += val
print(result)

a) Generates a random string of 9 characters consisting of numbers between 0 and 9.
b) Generates a random string of 9 characters consisting of numbers 0 and 1.
c) Generates a random string of 9 characters consisting of lowercase alphabets.
d) Generates a random string of 9 characters consisting of uppercase alphabets.

Correct answer is: b) Generates a random string of 9 characters consisting of numbers 0 and 1.
Explanation: The code imports the random module and initializes an empty string variable called “result”. It then enters a loop that iterates 9 times. In each iteration, it generates a random integer using `random.randint(0, 1)`, which will either be 0 or 1. This random integer is converted to a string using `str()`. The resulting string is then concatenated with the “result” variable.

12). 1. What is the output of the following code?

str1 = “abab”
test = []

for i in range(len(str1)):
    for j in range(i+1,len(str1)+1):
        test.append(str1[i:j])

dict1 = dict()
for val in test:
    dict1[val] = str1.count(val)
print(dict1)

a) {‘a’: 2, ‘ab’: 2, ‘aba’: 1, ‘abab’: 1, ‘b’: 2, ‘ba’: 1, ‘bab’: 1}
b) {‘a’: 4, ‘b’: 4, ‘ab’: 2, ‘ba’: 2}
c) {‘ab’: 2, ‘aba’: 1, ‘abab’: 1, ‘b’: 2, ‘ba’: 1, ‘bab’: 1}
d) {‘a’: 4, ‘b’: 4}

Correct answer is: a) {‘a’: 2, ‘ab’: 2, ‘aba’: 1, ‘abab’: 1, ‘b’: 2, ‘ba’: 1, ‘bab’: 1}
Explanation: The code generates all possible substrings of the string “abab” and stores them in the list `test`. Then, a dictionary `dict1` is created where the keys are the substrings and the values are the count of each substring in the original string. The output is the resulting dictionary.

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

string = “Sqatools”
print(“The index of q is: “, string.index(“q”))

a) The index of q is: 1
b) The index of q is: 2
c) The index of q is: 3
d) The index of q is: 4

Correct answer is: a) The index of q is: 1
Explanation: The index() method returns the index of the first occurrence of the specified substring within the string. In this case, the letter “q” is located at index 1 in the string “Sqatools”.

14). Which method is used to remove leading and trailing characters from a string?

a) remove()
b) trim()
c) strip()
d) clean()

Correct answer is: c) strip()
Explanation: The strip() method is used to remove leading and trailing characters from a string.

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

string = ” sqaltoolspythonfun “
print(string.strip())

a) “sqaltoolspythonfun”
b) ” sqaltoolspythonfun”
c) “sqaltoolspythonfun “
d) ” sqaltoolspythonfun “

Correct answer is: a) “sqaltoolspythonfun”
Explanation: The strip() method removes leading and trailing whitespace characters from a string. In this case, the leading and trailing spaces are removed, resulting in “sqaltoolspythonfun”.

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

string = “sqa,tools.python”
string.replace(“,”,”.”)

a) “sqa.tools.python”
b) “sqa,tools,python”
c) “sqa.tools,python”
d) “sqa.tools.python”

Correct answer is: a) “sqa.tools.python”
Explanation: The replace() method replaces all occurrences of the specified substring (“,”) with another substring (“.”). In this case, the comma (“,”) is replaced with a dot (“.”).

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

str1 = “l,e,a,r,n,I,n,g,p,y,t,h,o,n”
print(str1.rsplit(‘,’, 1))

a) [‘l,e,a,r,n,I,n,g,p,y,t,h’, ‘o,n’]
b) [‘l,e,a,r,n,I,n,g,p,y,t,h,o’, ‘n’]
c) [‘l,e,a,r,n,I,n,g,p,y,t,h’, ‘o’, ‘n’]
d) [‘l,e,a,r,n,I,n,g,p,y,t,h,o,n’]

Correct answer is: b) [‘l,e,a,r,n,I,n,g,p,y,t,h,o’, ‘n’]
Explanation: The rsplit() method splits the string into a list of substrings based on the specified separator. In this case, it splits the string at the last occurrence of ‘,’ and returns two substrings: ‘l,e,a,r,n,I,n,g,p,y,t,h,o’, and ‘n’.

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

str1 = “ab bc ca ab bd ca”
temp = []

for word in str1.split():
    if word in temp:
        print(“First repeated word: “, word)
        break
    else:
        temp.append(word)

a) First repeated word: ab
b) First repeated word: bc
c) First repeated word: ca
d) No repeated words found

Correct answer is: a) First repeated word: ab
Explanation: The given string contains the word “ab” twice, and it is the first repeated word encountered in the loop. Therefore, the output will be “First repeated word: ab”.

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

string1 = “python at sqatools”
str1 = “”

for char in string1:
    if char != ” “:
        str1 += char
print(str1)

a) “pythonatsqatools”
b) “python at sqatools”
c) “python”
d) “pythonatsqatools”

Correct answer is: a) “pythonatsqatools”
Explanation: The code removes all whitespace characters from string1 and assigns the result to str1. Therefore, str1 contains the original string without any spaces.

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

string = “this is my first program”

for char in string.split(” “):
    print(char[0].upper() + char[1:-1] + char[-1].upper(), end=” “)

a) ThiS IS MY FirsT PrograM
b) This is My First Program
c) T Is M First Progra
d) t Is y firs progra

Correct answer is: a) ThiS IS MY FirsT PrograM
Explanation: The code splits the string into a list of words using the space delimiter. Then, for each word, it capitalizes the first and last characters and keeps the rest of the word unchanged. The words are printed with a space separator.

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

string = “12sqatools78”
total = 0

for char in string:
    if char.isnumeric():
        total += int(char)
print(“Sum: “, total)

a) Sum: 0
b) Sum: 18
c) Sum: 20
d) Sum: 28

Correct answer is: b) Sum: 18
Explanation: The code iterates over each character in the string. If the character is numeric, it is converted to an integer using int(char) and added to the total variable. The numbers in the string are ‘1’, ‘2’, ‘7’, and ‘8’, which sum up to 18.

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

str1 = “aabbcceffgh”
from collections import Counter
str_char = Counter(str1)

part1 = [key for (key,count) in str_char.items() if count>1]
print(“Occurring more than once: “, “”.join(part1))

a) Occurring more than once: abcf
b) Occurring more than once: abcef
c) Occurring more than once: abcefg
d) Occurring more than once: aabbcceffgh

Correct answer is: a) Occurring more than once: abcf
Explanation: The code counts the occurrences of each character in the string and stores the result in str_char. It then creates a list part1 containing only the characters that appear more than once. Finally, it prints the characters joined together. In this case, the characters ‘a’, ‘b’, ‘c’, and ‘e’ appear more than once, so the output is “Occurring more than once: abce”.

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

str1 = “@SqaTools#lin”
upper = 0
lower = 0
digit = 0
symbol = 0

for val in str1:
    if val.isupper():
        upper += 1
    elif val.islower():
        lower += 1
    elif val.isdigit():
        digit += 1
    else:
        symbol += 1

print(“Uppercase: “, upper)
print(“Lowercase: “, lower)
print(“Digits: “, digit)
print(“Special characters: “, symbol)

a) Count the occurrences of uppercase, lowercase, digits, and special characters in a given string.
b) Validate if the string only contains uppercase letters.
c) Convert the string to uppercase and count the number of uppercase letters.
d) Check if the string contains any special characters.

Correct answer is: a) Count the occurrences of uppercase, lowercase, digits, and special characters in a given string.
Explanation: The code iterates over each character in the string and checks its properties using the isupper(), islower(), and isdigit() methods. It increments the respective counters (upper, lower, digit, and symbol) based on the character’s properties. Finally, it prints the count of each category.

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

string = “sqa****too^^{ls”
unwanted = [“#”, “*”, “!”, “^”, “%”,”{“,”}”]

for char in unwanted:
    string = string.replace(char,””)
print(string)

a) sqa****too^^{ls
b) sqatools
c) sqatoolsls
d) sqatoolsls**

Correct answer is: b) sqatools
Explanation: The code removes the characters in the unwanted list from the string using the replace() method. The unwanted characters are “*”, “!”, “^”, “%”, “{“, and “}”. After removing these characters, the resulting string is “sqatools”.

25). What is the output of the following code snippet?

str1 = “python 456 self learning 89”
list1 = []

for char in str1.split(” “):
    if char.isdigit():
        list1.append(int(char))
print(list1)

a) [456, 89]
b) [‘456′, ’89’]
c) [456, ’89’]
d) [‘python’, ‘self’, ‘learning’]

Correct answer is: a) [456, 89]
Explanation: The code splits the string str1 into a list of substrings using the delimiter ” “. It then iterates over each substring, checks if it consists only of digits using the isdigit() method, and if so, appends it as an integer to the list1 list. Finally, it prints the contents of list1, which will be [456, 89].

Leave a Comment