CCNA Strings Questions

72 of 181 questions · Page 2/3 · Strings topic · Answers revealed

76
Multi-Selecthard

Which TWO statements about Python strings are correct? (Choose exactly 2 correct answers.)

Select 2 answers
A.Strings are mutable; you can change individual characters via indexing.
B.Strings have an .append() method to add characters at the end.
C.Strings are immutable; operations like concatenation produce a new string.
D.The + operator on strings creates a new string object containing the concatenated result.
E.You can assign a new character to a position in a string using indexing: s[0] = 'a'.
AnswersC, D

Immutable means the string object cannot be modified; concatenation returns a new string.

Why this answer

Option B (strings are immutable) and Option D (concatenation creates a new string) are correct. Option A is wrong because strings are immutable, not mutable. Option C is wrong because .append() is not a method of strings; it belongs to lists.

Option E is wrong because item assignment is not allowed on strings (immutable).

77
MCQeasy

A developer wants to check if a string 'racecar' is a palindrome by comparing it to its reverse. Which code completes the task correctly?

A.reversed(s) == s
B.s[::1] == s
C.s[::-1] == s
D.s.reverse() == s
AnswerC

Slice with negative step reverses the string; comparison works.

Why this answer

Option B uses slicing with default step -1 to reverse the string and compares. Option A uses reversed() which returns an iterator, so comparison to a string fails. Option C uses .reverse() which is a list method.

Option D uses slicing but with step 1, which does not reverse.

78
MCQeasy

A developer needs to check if a string contains only alphanumeric characters. Which string method should be used?

A.s.isnumeric()
B.s.isalnum()
C.s.isdigit()
D.s.isalpha()
AnswerB

Returns True if all characters are alphanumeric (letters or digits).

Why this answer

Option B is correct because the `isalnum()` method returns `True` if all characters in the string are alphanumeric (letters or digits) and the string is non-empty. This directly matches the requirement to check for only alphanumeric characters, covering both letters and digits without any other characters.

Exam trap

The trap here is that candidates often confuse `isalnum()` with `isalpha()` or `isdigit()`, mistakenly thinking that checking for letters only or digits only is sufficient, when the question explicitly requires both letters and digits (alphanumeric).

How to eliminate wrong answers

Option A is wrong because `isnumeric()` returns `True` only for numeric characters (including Unicode numeric values like fractions, Roman numerals, etc.), not for letters, so it fails to check for alphanumeric content. Option C is wrong because `isdigit()` returns `True` only for decimal digit characters (0-9 and certain Unicode digits), excluding letters entirely. Option D is wrong because `isalpha()` returns `True` only for alphabetic characters (letters), excluding digits, so it would reject strings containing numbers.

79
MCQhard

A developer is tasked with validating user input that must be a 10-digit phone number. The input may contain spaces, dashes, and parentheses. Which approach best ensures the input contains exactly 10 digits?

A.if len([c for c in s if c.isdigit()]) == 10:
B.if len(s) >= 10 and s.isdigit():
C.if s[:10].isdigit():
D.if s.isdigit() and len(s) == 10:
AnswerA

This extracts all digits and checks if there are exactly 10, ignoring non-digits.

Why this answer

Option A uses a list comprehension to filter only digit characters from the input string `s` and then checks if the count of those digits is exactly 10. This correctly handles any non-digit characters (spaces, dashes, parentheses) by ignoring them, ensuring the validation focuses solely on the presence of exactly ten digits.

Exam trap

Python Institute often tests the distinction between checking if a string *contains* a certain number of digits versus checking if the string *itself* is entirely composed of digits, leading candidates to mistakenly choose options that require the entire string to be numeric.

How to eliminate wrong answers

Option B is wrong because `s.isdigit()` returns `True` only if *all* characters in the string are digits, so it would reject valid inputs containing spaces, dashes, or parentheses. Option C is wrong because `s[:10].isdigit()` only checks the first ten characters, ignoring any non-digit characters that might appear later, and also fails to verify that the entire string contains exactly ten digits (e.g., a 15-digit string with first ten digits would incorrectly pass). Option D is wrong because `s.isdigit()` again requires the entire string to consist solely of digits, which would reject any input with formatting characters, even if it contains exactly ten digits.

80
MCQhard

What is the output of the code?

A.['support@example', 'sales@example']
B.[]
C.['support@example.com', 'sales@example.org']
D.['support@example.com']
AnswerC

Both email addresses match the pattern.

Why this answer

The code uses `re.findall()` with the pattern `r'\b\w+@\w+\.\w{2,4}\b'`. This pattern matches word boundaries, one or more word characters, an '@', one or more word characters, a dot, and 2-4 word characters (the TLD). The string contains 'support@example.com' and 'sales@example.org', both of which satisfy the pattern, so they are returned as a list.

Option C is correct because the regex correctly extracts both email addresses.

Exam trap

Python Institute often tests the misconception that `re.findall()` returns only the first match or that the regex fails due to the dot not being escaped, but here the dot is correctly escaped with `\.` and the pattern matches all occurrences, so candidates who think the dot is a wildcard or that the pattern is invalid may incorrectly choose B or D.

How to eliminate wrong answers

Option A is wrong because it omits the TLDs '.com' and '.org', suggesting the regex stopped at the dot, but the pattern explicitly requires a dot followed by 2-4 word characters. Option B is wrong because it assumes no matches occur, but the pattern does match both valid email addresses in the string. Option D is wrong because it includes only 'support@example.com', missing 'sales@example.org', which also matches the pattern; the regex is not case-sensitive or selective in a way that would exclude the second address.

81
MCQhard

Refer to the exhibit. What is the likely outcome of running this code?

A.The program raises a SyntaxError due to invalid escape sequences.
B.The program runs but the file contents are incorrect.
C.The program raises a FileNotFoundError because the path is invalid after escape interpretation.
D.The file is opened successfully because backslashes are ignored.
AnswerA

Correct: \U is an invalid escape sequence in Python.

Why this answer

Option A is correct because the code contains backslash sequences like `\n` and `\t` that are not valid escape sequences in Python. Python 3.12+ raises a `SyntaxError: invalid escape sequence` by default, and in earlier versions it emits a `DeprecationWarning` that will become an error in future versions. The raw string prefix `r` or escaping the backslash (`\\`) is required to avoid this.

Exam trap

Python Institute often tests the misconception that backslashes in strings are always treated literally or that invalid escape sequences are silently ignored, leading candidates to choose options about file operations instead of recognizing the compile-time SyntaxError.

How to eliminate wrong answers

Option B is wrong because the program does not run at all; a SyntaxError prevents execution, so no file is written or read. Option C is wrong because the error is a SyntaxError at compile time, not a runtime FileNotFoundError; the path string is never evaluated as a file path. Option D is wrong because backslashes are not ignored; they are interpreted as escape sequences, and invalid ones cause a SyntaxError.

82
MCQmedium

You are a data analyst working with a dataset of customer reviews. Each review is stored as a string in a list. You need to count how many reviews contain the word 'excellent' (case-insensitive). However, the word might appear as 'Excellent', 'EXCELLENT', or even with punctuation like 'excellent!'. The current code uses 'excellent' in review.lower(), but this fails if 'excellent' is part of another word like 'unexcellent'. You need to ensure that only the whole word 'excellent' is counted. Which code modification will correctly count whole word occurrences?

A.Use re.search(r'\bexcellent\b', review, re.IGNORECASE)
B.Use 'excellent' in review.lower().split()
C.Use review.lower().count('excellent') > 0
D.Use review.lower().find('excellent') != -1
AnswerA

Word boundary regex ensures whole word match regardless of case.

Why this answer

Option A is correct because `re.search(r'\bexcellent\b', review, re.IGNORECASE)` uses the `\b` word boundary anchor to ensure that 'excellent' is matched as a whole word, not as part of another word like 'unexcellent'. The `re.IGNORECASE` flag handles case-insensitive matching, covering 'Excellent', 'EXCELLENT', etc. This approach also correctly handles punctuation attached to the word, such as 'excellent!', because the word boundary matches between a word character and a non-word character.

Exam trap

Python Institute often tests the distinction between substring matching and whole-word matching, and the trap here is that candidates assume `in` with `split()` or `count()` handles whole words, but they fail to account for punctuation or compound words, leading to incorrect counts.

How to eliminate wrong answers

Option B is wrong because `'excellent' in review.lower().split()` splits the string on whitespace only, so it would fail if 'excellent' is followed by punctuation like 'excellent!' (the split would keep the exclamation mark attached, making the word 'excellent!' not equal to 'excellent'). Option C is wrong because `review.lower().count('excellent') > 0` counts substring occurrences, so it would match 'excellent' inside 'unexcellent' and count it incorrectly. Option D is wrong because `review.lower().find('excellent') != -1` also performs a substring search, matching 'excellent' as part of a larger word like 'unexcellent'.

83
Multi-Selecthard

Which three of the following statements about Python strings are true? (Choose three.)

Select 3 answers
A.The join() method is called on the separator string.
B.The string '123.45' can be converted to integer using int('123.45').
C.Strings support indexing with integers.
D.Strings are mutable.
E.The len() function returns the number of characters including spaces.
AnswersA, C, E

For example: ','.join(list) joins list elements with comma.

Why this answer

B is true: strings support integer indexing. C is true: len() counts all characters. D is true: join() is called on the separator.

A is false: strings are immutable. E is false: int() cannot convert a string with a decimal point.

84
MCQeasy

What is the output of the code in the exhibit?

A.{name} is {age} years old.
B.Alice is 30 years old.
C.Alice is 30 years old.
D.30 is Alice years old.
AnswerB

The f-string correctly interpolates the variables.

Why this answer

Option A is correct because the f-string substitutes the variables name and age. Option B has incorrect formatting with curly braces. Option C places age before name.

Option D uses incorrect variable names.

85
MCQeasy

A junior developer is writing a script that processes user input. The script reads a line of text from the console and needs to remove any leading or trailing whitespace. The developer uses the strip() method but notices that it also removes other characters like newline. However, the requirement is to remove only spaces (not tabs or newlines). Which course of action should the developer take to remove only leading and trailing spaces?

A.Use replace(' ', '') on the string
B.Use lstrip() and rstrip() with no arguments
C.Use split() and join()
D.Use strip(' ') with a space argument
AnswerD

Correct: strip() with specified characters removes only those characters from the ends.

Why this answer

The strip() method without arguments removes all whitespace, including tabs and newlines. To remove only spaces, use strip(' ') which removes only the space character. lstrip() and rstrip() with no arguments also remove all whitespace. replace() removes all spaces everywhere, not just at ends. split() and join() would remove and rejoin with default separator, altering the string.

86
MCQhard

Given the code: s = 'Python'; t = s; s = s + '3.0'. What is the value of t after these lines execute?

A.It raises an error because s was reassigned.
B.''
C.'Python3.0'
D.'Python'
AnswerD

t originally pointed to the same object as s, but when s is reassigned, t still references the original 'Python'.

Why this answer

Option D is correct because strings in Python are immutable. The assignment `t = s` makes `t` reference the same string object as `s`. When `s = s + '3.0'` executes, a new string object `'Python3.0'` is created and bound to `s`, while `t` still references the original string `'Python'`.

Thus, `t` remains `'Python'`.

Exam trap

Python Institute often tests the misconception that variable assignment creates a copy of the value, when in fact it creates a reference; candidates mistakenly think `t` will reflect the new value of `s` after reassignment.

How to eliminate wrong answers

Option A is wrong because reassigning `s` does not raise an error; Python allows variable reassignment freely. Option B is wrong because `t` is never assigned an empty string; it is assigned the original value of `s`, which is `'Python'`. Option C is wrong because `t` does not get updated when `s` is reassigned; `t` still points to the original immutable string `'Python'`, not the new concatenated string `'Python3.0'`.

87
MCQmedium

A developer needs to count the number of occurrences of the substring 'is' in the string 'This is a test. Is this a test?'. Which code correctly performs the count?

A.'This is a test. Is this a test?'.split().count('is')
B.'This is a test. Is this a test?'.count('is')
C.'This is a test. Is this a test?'.index('is')
D.'This is a test. Is this a test?'.find('is')
AnswerB

Correctly counts overlapping? No, count does not count overlapping, but 'is' appears at positions 5 and 17, not overlapping, so returns 2.

Why this answer

Option B is correct because Python's string method `count(substring)` returns the number of non-overlapping occurrences of the substring in the string. In 'This is a test. Is this a test?', 'is' appears twice (in 'This' and 'is'), and the method counts them correctly, ignoring case sensitivity (the capitalized 'Is' is not counted).

Exam trap

Python Institute often tests the distinction between string methods that return indices (`find`, `index`) versus those that return counts (`count`), and the trap here is that candidates confuse `count()` with `find()` or `index()`, or incorrectly assume `split().count()` works for substring counting.

How to eliminate wrong answers

Option A is wrong because `split()` breaks the string into a list of words (e.g., ['This', 'is', 'a', 'test.', 'Is', 'this', 'a', 'test?']), and then `count('is')` on that list counts only exact list element matches, not substring occurrences — it would return 1 (for the word 'is'), not 2. Option C is wrong because `index('is')` returns the index of the first occurrence of the substring (2) and raises a ValueError if not found, not a count. Option D is wrong because `find('is')` returns the index of the first occurrence (2) or -1 if not found, not a count.

88
MCQhard

Refer to the exhibit. What is the output?

A.'100'
B.100
C.True
D.Error
AnswerB

The integer value 100.

Why this answer

The code `print('100')` outputs the string `100` without quotes. In Python, `print()` displays the value passed to it; when a string literal is passed, it prints the characters of the string, not the surrounding quotes. Therefore, the output is `100` (the integer-like string, but as a string).

Option B is correct because it shows the numeric value without quotes, which is how Python's `print()` renders a string.

Exam trap

The trap here is that candidates confuse the string literal representation (with quotes) with the printed output, mistakenly thinking that `print('100')` will display the quotes as part of the output.

How to eliminate wrong answers

Option A is wrong because it shows the output with single quotes around `100`, but Python's `print()` function does not include quotes in the output; quotes are only used in the source code to denote a string literal. Option C is wrong because `'100'` is a string, not a boolean; printing it does not produce `True` or `False`. Option D is wrong because the code is syntactically valid and runs without error; `print('100')` is a standard Python statement.

89
Multi-Selectmedium

Which TWO are valid ways to create a multiline string in Python?

Select 2 answers
A.s = ('Line1\n' 'Line2')
B.s = """Line1 Line2"""
C.s = '''Line1 Line2'''
D.s = "Line1\ Line2"
E.s = 'Line1 Line2'
AnswersA, B

Implicit string concatenation with newline escape.

Why this answer

Option A is correct because Python allows implicit string concatenation: adjacent string literals (even across lines within parentheses) are joined into a single string at compile time. The newline escape sequence `\n` in the first literal produces a multiline string without a physical line break in the source code.

Exam trap

Python Institute often tests the distinction between physical line continuation (backslash) and actual multiline string creation (triple quotes or implicit concatenation with `\n`), trapping candidates who think a backslash at line end produces a multiline string.

90
MCQhard

Refer to the exhibit. What is the output?

A.Hi, World!
B.Hello, World!
C.HELLO, WORLD!
D.HI, WORLD!
AnswerD

Correct after both operations.

Why this answer

The correct answer is D because the code uses the `upper()` method on the string `'Hi, World!'`, which converts all lowercase letters to uppercase. The output is `'HI, WORLD!'`. The `upper()` method does not modify the original string but returns a new string with all characters in uppercase.

Exam trap

Python Institute often tests whether candidates notice the exact original string value, as many mistakenly assume the output is 'HELLO, WORLD!' from a common greeting like 'Hello, World!' rather than the actual string 'Hi, World!'.

How to eliminate wrong answers

Option A is wrong because it shows the original string unchanged, but the `upper()` method was called, so the output must be all uppercase. Option B is wrong because it shows 'Hello, World!' which is a different string entirely, not the result of calling `upper()` on `'Hi, World!'`. Option C is wrong because it shows 'HELLO, WORLD!' which would be the result of calling `upper()` on 'Hello, World!', not on 'Hi, World!'.

91
MCQhard

Which of the following expressions returns True if the string s contains only hexadecimal digits (0-9, a-f, A-F)?

A.s.isdigit() or s.isalpha()
B.s.isnumeric()
C.s.isalnum() and s.islower()
D.all(c in '0123456789abcdefABCDEF' for c in s)
AnswerD

Correct: Checks each character against the set of valid hex digits.

Why this answer

The most reliable way is to check each character against a set of valid hex digits. Option C does exactly that. Other options are too broad or incorrect.

92
MCQmedium

A function is supposed to return True if a string contains only digits, and False otherwise. Which implementation uses a Python string method correctly?

A.return s.isdecimal()
B.return s.isnumeric()
C.return s.isalnum() and not s.isalpha()
D.return s.isdigit()
AnswerD

Correctly returns True for strings containing only digits.

Why this answer

isdigit() checks if all characters in the string are digits (0-9 and other Unicode digits), which is the standard method for this purpose.

93
MCQhard

Given the string s = 'Hello World!', which expression returns a list of characters?

A.s.split('')
B.list(s)
C.s.split()
D.s.split(' ')
AnswerB

Converts string to list of characters.

Why this answer

Option B is correct because the `list()` constructor, when passed a string, iterates over each character in the string and returns a list where each element is a single character. For `s = 'Hello World!'`, `list(s)` produces `['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!']`, which is exactly a list of characters.

Exam trap

Python Institute often tests the distinction between `list(s)` and `s.split()` to catch candidates who confuse splitting a string into words with converting it into a list of characters, especially when the delimiter is omitted or set to an empty string.

How to eliminate wrong answers

Option A is wrong because `s.split('')` raises a `ValueError: empty separator` in Python; the `split()` method requires a non-empty separator string. Option C is wrong because `s.split()` with no arguments splits on any whitespace and discards empty strings, returning `['Hello', 'World!']`, which is a list of words, not characters. Option D is wrong because `s.split(' ')` splits on a single space character, returning `['Hello', 'World!']`, again a list of words, not individual characters.

94
Multi-Selecthard

Given s = 'a1b2c3', which TWO of the following expressions return the string '123'?

Select 2 answers
A.s[0:5:2]
B.s[1::2]
C.s[1:6:2]
D.s[0::2]
E.s[2:5:1]
AnswersB, C

Step 2 from index 1: '1', '2', '3'.

Why this answer

Option B is correct because slicing with `s[1::2]` starts at index 1 (the character '1'), goes to the end of the string, and takes every second character, resulting in '1', '2', '3' concatenated as '123'. Option C is also correct because `s[1:6:2]` starts at index 1, stops before index 6 (the string length is 6, so index 6 is just past the last character), and steps by 2, yielding the same sequence of characters.

Exam trap

Python Institute often tests the misconception that slicing with a step of 2 always starts from index 0, causing candidates to overlook the correct starting index needed to isolate digits from a mixed string.

95
Multi-Selectmedium

Which TWO of the following can be used to remove leading whitespace (spaces, tabs, newlines) from a string? (Choose exactly 2 correct answers.)

Select 2 answers
A.rstrip()
B.lstrip()
C.trim()
D.clean()
E.strip()
AnswersB, E

lstrip() specifically removes leading whitespace.

Why this answer

Option A (lstrip()) removes leading whitespace. Option D (strip()) removes both leading and trailing whitespace, which includes leading whitespace. Option B (rstrip()) removes trailing, not leading.

Option C (trim()) is not a Python string method. Option E (clean()) does not exist.

96
MCQmedium

A developer wants to remove leading and trailing whitespace from a string. Which method should be used?

A.s.lstrip()
B.s.trim()
C.s.rstrip()
D.s.strip()
AnswerD

Removes whitespace from both ends.

Why this answer

Option D is correct because the `strip()` method in Python removes both leading and trailing whitespace (including spaces, tabs, and newlines) from a string. This is the standard method for trimming whitespace from both ends, as specified in Python's string documentation.

Exam trap

Python Institute often tests the distinction between `strip()`, `lstrip()`, and `rstrip()`, and the trap here is that candidates may confuse `strip()` with the non-existent `trim()` method from other languages, or think `lstrip()` or `rstrip()` alone suffice for full trimming.

How to eliminate wrong answers

Option A is wrong because `lstrip()` only removes leading whitespace from the left side, not trailing whitespace. Option B is wrong because `trim()` is not a valid Python string method; it exists in other languages like Java or JavaScript but not in Python. Option C is wrong because `rstrip()` only removes trailing whitespace from the right side, not leading whitespace.

97
MCQmedium

Which of the following is the correct way to format a string to include a variable value with two decimal places in Python?

A.f"{value:.2f}"
B.f"{value:.2}"
C.f"{value%:.2f}"
D.f"{value:2f}"
AnswerA

Correct: :.2f formats with two decimal places.

Why this answer

In an f-string, the format specifier :.2f is used to format a float with two decimal places. Option B is the correct syntax.

98
MCQeasy

A developer needs to check if a filename starts with the prefix 'report_'. Which string method should be used?

A.prefix()
B.startswith()
C.starts()
D.beginwith()
AnswerB

Correct because str.startswith(prefix) checks the start of the string.

Why this answer

The `startswith()` method is the correct string method in Python to check if a string begins with a specified prefix. It returns `True` if the string starts with the given substring, otherwise `False`, making it the exact tool for checking if a filename starts with 'report_'.

Exam trap

Python Institute often tests the exact naming of Python string methods, and the trap here is that candidates may confuse `startswith()` with similar-sounding but non-existent methods like `starts()` or `beginwith()`, or incorrectly assume a method like `prefix()` exists based on other programming languages.

How to eliminate wrong answers

Option A is wrong because `prefix()` is not a valid Python string method; no such method exists in the standard library. Option C is wrong because `starts()` is not a valid Python string method; the correct method name is `startswith()`. Option D is wrong because `beginwith()` is not a valid Python string method; Python uses `startswith()` for this purpose, not `beginwith()`.

99
Multi-Selecteasy

Which TWO of the following string methods return a boolean value?

Select 2 answers
A.startswith()
B.capitalize()
C.format()
D.swapcase()
E.isalpha()
AnswersA, E

Returns True or False.

Why this answer

The `startswith()` method returns `True` if the string starts with the specified prefix, otherwise `False`. Similarly, `isalpha()` returns `True` if all characters in the string are alphabetic and there is at least one character, otherwise `False`. Both methods explicitly return a boolean value (`True` or `False`), making them correct choices.

Exam trap

The trap here is that candidates often confuse methods that return a new string (like `capitalize()`, `swapcase()`) with methods that return a boolean, because both are called on string objects and appear similar in syntax.

100
MCQeasy

A developer is writing a function that validates a user input string to ensure it contains only ASCII digits (0-9) for a numeric ID field. Which method should be used to check the string?

A.isdecimal()
B.isnumeric()
C.isdigit()
D.isalpha()
AnswerC

isdigit() returns True for all digit characters, including ASCII digits 0-9, and is the appropriate check.

Why this answer

Option C is correct because isdigit() returns True for strings that consist only of decimal digits (0-9) in the Unicode sense, but for ASCII digits it works correctly. Option A (isnumeric()) also returns True for numeric characters like '½', so it is too broad. Option B (isdecimal()) is limited to decimal numbers and can fail on some digits.

Option D (isalpha()) checks for alphabetic characters only.

101
MCQmedium

You are a developer for an e-commerce platform. The system receives product descriptions from suppliers in various formats. One supplier sends descriptions with inconsistent capitalization, extra whitespace, and occasional leading/trailing punctuation. Your task is to write a function that normalizes these descriptions: convert to lowercase, remove leading/trailing whitespace and punctuation (.,!?;:), and replace multiple spaces with a single space. The function should return the cleaned string. Which implementation correctly performs all these steps?

A.def normalize(s): import re; s = s.strip(); s = s.strip('.,!?;:'); s = s.lower(); s = re.sub(r'\s+', ' ', s); return s
B.def normalize(s): return ' '.join(s.lower().split())
C.def normalize(s): return s.lower().strip('.,!?;: ')
D.def normalize(s): return s.strip().lower()
AnswerA

Correctly strips whitespace, then punctuation, lowercases, and collapses spaces.

Why this answer

Option A is correct because it performs all required steps in the correct order: it first strips leading/trailing whitespace with `strip()`, then removes leading/trailing punctuation using `strip('.,!?;:')`, converts to lowercase with `lower()`, and finally replaces multiple spaces with a single space using `re.sub(r'\s+', ' ', s)`. This ensures that punctuation is removed only from the edges after whitespace is handled, and internal whitespace is normalized last.

Exam trap

Python Institute often tests the order of operations in string normalization, and the trap here is that candidates may think `strip()` with a punctuation argument also handles whitespace or that `split()` and `join()` alone are sufficient to remove punctuation, leading them to choose options that miss one or more required steps.

How to eliminate wrong answers

Option B is wrong because it uses `split()` which splits on any whitespace and removes it entirely, but it does not remove leading/trailing punctuation (e.g., '!Hello' becomes '!hello' after `lower()` and split/join, leaving the exclamation mark). Option C is wrong because `strip('.,!?;: ')` removes only leading/trailing characters from that set, but it does not replace multiple internal spaces with a single space (e.g., 'Hello World' stays with multiple spaces). Option D is wrong because it only strips whitespace and lowercases, ignoring the removal of leading/trailing punctuation and the normalization of multiple internal spaces.

102
MCQeasy

A programmer has a string 'apple,banana,orange' and wants to get a list ['apple', 'banana', 'orange']. Which method should be used?

A.s.splitlines()
B.s.partition(',')
C.s.join(',')
D.s.split(',')
AnswerD

split(',') returns a list of substrings separated by commas.

Why this answer

Option B is correct because str.split(',') splits the string on the comma. Option A is wrong because str.partition() returns a tuple of three parts. Option C is wrong because str.splitlines() splits on line breaks.

Option D is wrong because str.join() is the inverse operation.

103
MCQmedium

A programmer has a string s = 'Python programming is fun'. They want to extract the word 'programming'. Which slicing expression achieves this?

A.s[6:18]
B.s[7:18]
C.s[7:19]
D.s[6:19]
AnswerB

Correct: Extracts indices 7 to 17, which is 'programming'.

Why this answer

The word 'programming' starts at index 7 and ends at index 17 (inclusive). Slicing s[7:18] extracts indices 7 through 17.

104
MCQmedium

A logging module receives a message that may contain sensitive data. To comply with data privacy, all digits in the message should be replaced with 'X' before logging. Which approach correctly achieves this?

A.message.replace('0-9', 'X')
B.re.sub(r'[0-9]', 'X', message)
C.message.translate(str.maketrans('0123456789', 'XXXXXXXXXX'))
D.''.join(['X' if c.isdigit() else c for c in message])
AnswerB

Uses regex to replace any digit character with 'X'.

Why this answer

Option B is correct because `re.sub(r'[0-9]', 'X', message)` uses a regular expression character class `[0-9]` to match any single digit (0-9) and replaces each occurrence with 'X'. This is the standard Python approach for pattern-based string replacement, and it correctly handles all digits without affecting non-digit characters.

Exam trap

Python Institute often tests the distinction between literal string methods (`str.replace()`) and pattern-based methods (`re.sub()`), trapping candidates who assume `replace()` can interpret character ranges like `'0-9'` as a regex pattern.

How to eliminate wrong answers

Option A is wrong because `message.replace('0-9', 'X')` treats the string `'0-9'` as a literal substring to replace, not as a range of digits; it will only replace the exact sequence '0-9' if it appears in the message. Option C is wrong because `str.maketrans('0123456789', 'XXXXXXXXXX')` creates a translation table that maps each digit character to 'X', but `message.translate()` returns a new string with the replacements applied; while this would technically work, it is not the most direct or idiomatic approach for this task, and the question asks for the approach that 'correctly achieves this' — Option B is more standard and less error-prone. Option D is wrong because it uses a list comprehension with `c.isdigit()` to replace digits with 'X', which is functionally correct but is not a method of the string class; it is a valid Python expression but not a string method, and the question implies using a string method or a direct replacement approach.

105
MCQeasy

Which of the following is a valid way to create an empty string in Python?

A.empty = str()
B.empty = ''
C.Both A and B
D.empty = ""
AnswerC

Both are valid ways to create an empty string.

Why this answer

Both `str()` and `''` (as well as `""`) are valid ways to create an empty string in Python. `str()` calls the built-in `str` constructor with no arguments, which returns an empty string object, while `''` and `""` are literal empty string syntax. Since all three produce the same immutable empty string object, option C is correct.

Exam trap

Python Institute often tests the distinction between `str()` and string literals, and the trap here is that candidates may think `str()` requires an argument or that only one of the literal forms is valid, when in fact both `''` and `""` are identical and `str()` without arguments returns an empty string.

How to eliminate wrong answers

Option A is wrong because it is actually a valid way to create an empty string, so it is not incorrect. Option B is wrong because it is also a valid way to create an empty string, so it is not incorrect. Option D is wrong because `""` is a valid empty string literal in Python, so it is not incorrect.

The only correct answer is C, which states that both A and B are valid.

106
MCQeasy

What is the result of the expression 'aBc'.lower()?

A.'abc'
B.'Abc'
C.'aBc'
D.'ABC'
AnswerA

All characters are converted to lowercase.

Why this answer

The `lower()` method returns a new string with all cased characters converted to lowercase. Since the original string 'aBc' contains an uppercase 'B', calling `.lower()` converts it to 'b', resulting in 'abc'. The method does not modify the original string but returns a new one.

Exam trap

Python Institute often tests whether candidates understand that `.lower()` does not modify the original string but returns a new one, and that it only affects uppercase letters, not other characters like digits or symbols.

How to eliminate wrong answers

Option B is wrong because 'Abc' would result from calling `.capitalize()` or `.title()`, not `.lower()`. Option C is wrong because it is the original string unchanged, but `.lower()` always returns a new string with all characters lowercased. Option D is wrong because 'ABC' would result from calling `.upper()`, not `.lower()`.

107
MCQmedium

A programmer needs to replace every occurrence of 'cat' with 'dog' in a string s, but only if 'cat' is not preceded by 'big'. Which regex substitution would achieve this?

A.re.sub(r'bigcat', 'dog', s)
B.re.sub(r'cat', 'dog', s)
C.re.sub(r'(?<=big)cat', 'dog', s)
D.re.sub(r'(?<!big)cat', 'dog', s)
AnswerD

Uses negative lookbehind to ignore 'cat' when preceded by 'big'.

Why this answer

Option C uses negative lookbehind to exclude 'bigcat' from replacement. Option A replaces all 'cat'. Option B replaces 'bigcat'.

Option D replaces only 'cat' preceded by 'big'.

108
MCQeasy

What is the output of 'hello'.count('l')?

A.1
B.3
C.0
D.2
AnswerD

Correct, 'hello' contains two 'l' characters.

Why this answer

The string method `count('l')` returns the number of non-overlapping occurrences of the substring `'l'` in the string `'hello'`. The string `'hello'` contains the character `'l'` at indices 2 and 3, so the count is 2. Therefore, option D is correct.

Exam trap

Python Institute often tests the `count()` method with a single character substring to see if candidates correctly count occurrences, but the trap here is that some candidates might mistakenly count the total number of characters or misremember the string `'hello'` as having only one `'l'`.

How to eliminate wrong answers

Option A is wrong because it suggests only one `'l'` is present, but `'hello'` has two `'l'` characters. Option B is wrong because it counts three `'l'` characters, which would be true only for a string like `'lll'` or if the candidate mistakenly counts the `'l'` in `'hello'` three times. Option C is wrong because it indicates no `'l'` is found, which is incorrect as `'hello'` clearly contains two `'l'` characters.

109
MCQmedium

Which of the following demonstrates that strings are immutable?

A.s.upper() changes s in place
B.s[0] = 'J' results in a TypeError
C.s += '!' modifies s
D.s.replace('a','b') modifies s
AnswerB

Correct: strings are immutable, so item assignment is not allowed.

Why this answer

Option B is correct because attempting to assign a new character to an index of a string (e.g., s[0] = 'J') raises a TypeError, which directly demonstrates that strings are immutable in Python. Immutability means the object's value cannot be changed after creation; any operation that appears to modify a string actually creates a new string object.

Exam trap

Python Institute often tests the misconception that methods like upper(), replace(), or the += operator modify the original string in place, when in fact they always return a new string object, and the trap is that candidates confuse variable rebinding with in-place mutation.

How to eliminate wrong answers

Option A is wrong because s.upper() does not change s in place; it returns a new string with all uppercase characters, leaving the original string s unchanged. Option C is wrong because s += '!' does not modify the original string in place; it creates a new string object and rebinds the variable s to that new object, while the original string remains unchanged. Option D is wrong because s.replace('a','b') does not modify s; it returns a new string with the replacements applied, and the original string s is unaffected.

110
MCQmedium

What is the result of 'Python'.find('th')?

A.1
B.-1
C.2
D.0
AnswerC

'th' starts at index 2.

Why this answer

The string method `find()` returns the lowest index where the substring is found. In 'Python', the substring 'th' starts at index 2 (P=0, y=1, t=2, h=3, o=4, n=5). Therefore, the result is 2, making option C correct.

Exam trap

Python Institute often tests the zero-based indexing of strings, leading candidates to mistakenly count from 1 instead of 0, or to confuse `find()` with `index()` and expect an exception for missing substrings.

How to eliminate wrong answers

Option A is wrong because 1 would be the index of 'y', not the start of 'th'. Option B is wrong because -1 is returned only when the substring is not found, but 'th' is present in 'Python'. Option D is wrong because 0 would be the index of 'P', not the start of 'th'.

111
Drag & Dropmedium

Drag and drop the steps to debug a Python script using pdb into the correct order.

Drag steps to the numbered slots on the right, or tap a step then tap a slot.

Steps
Order

Why this order

Debugging with pdb involves setting a trace, running the script, using commands to step through code, setting breakpoints, and exiting.

112
MCQeasy

A user entered a string ' Hello, World! '. Which expression returns 'Hello, World!'?

A.s.split()
B.s.strip()
C.s.rstrip()
D.s.lstrip()
AnswerB

strip() removes whitespace from both ends.

Why this answer

The `strip()` method removes all leading and trailing whitespace characters from a string, returning a new string without the surrounding spaces. In this case, `s.strip()` removes the three leading spaces and three trailing spaces from ' Hello, World! ', resulting in 'Hello, World!'.

Exam trap

Python Institute often tests the distinction between `strip()`, `lstrip()`, and `rstrip()` by presenting a string with both leading and trailing whitespace, tempting candidates to choose a partial removal method when only the full `strip()` works.

How to eliminate wrong answers

Option A is wrong because `split()` without arguments splits the string on any whitespace and returns a list of substrings, not a single string; it would produce ['Hello,', 'World!'] (or similar depending on whitespace). Option C is wrong because `rstrip()` only removes trailing whitespace, leaving the leading spaces intact, so it would return ' Hello, World!'. Option D is wrong because `lstrip()` only removes leading whitespace, leaving the trailing spaces intact, so it would return 'Hello, World! '.

113
Multi-Selecthard

Which THREE methods return a boolean value?

Select 3 answers
A.str.upper()
B.str.startswith()
C.str.islower()
D.str.isalpha()
E.str.find()
AnswersB, C, D

Returns True or False.

Why this answer

B is correct because str.startswith() returns True if the string starts with the specified prefix, otherwise False. It is a boolean-returning method, as required by the question.

Exam trap

Python Institute often tests the distinction between methods that return a boolean versus those that return a new string or an integer, leading candidates to mistakenly select str.upper() or str.find() because they think any method that checks a condition returns a boolean.

114
MCQmedium

A developer is working on a logging system where dynamic values are inserted into a template string. The template is 'User %s logged in at %s'. The developer has the username and timestamp as separate variables. Which approach is most Pythonic (PEP 498) and recommended for new code?

A.Use %-formatting: 'User %s logged in at %s' % (username, timestamp)
B.Use .format(): 'User {} logged in at {}'.format(username, timestamp)
C.Concatenate: 'User ' + username + ' logged in at ' + timestamp
D.Use an f-string: f'User {username} logged in at {timestamp}'
AnswerD

f-strings are the recommended approach for string formatting in Python 3.6+.

Why this answer

Option C (f-string) is the most Pythonic and recommended for new code per PEP 498. Option A (% formatting) is older. Option B (.format()) is also fine but f-strings are often preferred for readability when variables are available.

Option D (concatenation) is prone to errors and less readable.

115
MCQmedium

When processing a large text file, a developer notices that using str.replace() in a loop is slow. Which alternative is most efficient for multiple replacements?

A.Use str.maketrans() on the original string
B.Use re.sub() from the re module
C.Use str.translate() with a translation table
D.Chain multiple str.replace() calls
AnswerC

str.translate() performs all replacements in a single pass.

Why this answer

Option C is correct because `str.translate()` with a translation table built by `str.maketrans()` performs all character replacements in a single pass over the string, operating at the C level in CPython. This avoids the O(n) per-replacement overhead of `str.replace()` in a loop, making it the most efficient choice for multiple, fixed-character substitutions on large text.

Exam trap

Python Institute often tests the misconception that `str.maketrans()` alone performs replacements, when in fact it only generates the table required by `str.translate()`, leading candidates to mistakenly select option A.

How to eliminate wrong answers

Option A is wrong because `str.maketrans()` only creates a translation table; it does not perform any replacement itself and must be used with `str.translate()` to be effective. Option B is wrong because `re.sub()` uses a regex engine that compiles patterns and backtracks, incurring significant overhead for simple, fixed-character replacements compared to a direct translation table. Option D is wrong because chaining multiple `str.replace()` calls processes the entire string multiple times (once per call), leading to O(n*m) complexity where m is the number of replacements, which is inefficient for large files.

116
MCQhard

A developer writes: s = 'abc'; s[0] = 'x'. What happens?

A.s becomes 'xbc'
B.TypeError: 'str' object does not support item assignment
C.ValueError: string index out of range
D.s becomes 'abc' and no error
AnswerB

This is the exact error raised.

Why this answer

In Python, strings are immutable, meaning their contents cannot be changed after creation. Attempting to assign a new character to an index position (e.g., `s[0] = 'x'`) raises a `TypeError: 'str' object does not support item assignment`. This is a fundamental property of the `str` type in Python, enforced at the interpreter level.

Exam trap

Python Institute often tests the immutability of strings by presenting an assignment to an index, tricking candidates who confuse strings with mutable sequences like lists.

How to eliminate wrong answers

Option A is wrong because it assumes strings are mutable like lists, but Python strings are immutable and cannot be modified in-place. Option C is wrong because the index 0 is valid for a string of length 3, so no `IndexError` or `ValueError` occurs; the error is about assignment, not indexing. Option D is wrong because Python does not silently ignore invalid assignments; it raises an exception immediately.

117
Multi-Selecthard

Which THREE of the following are valid ways to create a string in Python?

Select 3 answers
A.'Hello'
B.'Hello'
C.f'{name}'
D.`Hello`
E.'''Hello'''
AnswersB, C, E

Single quotes are valid string delimiters.

Why this answer

Option B is correct because single quotes are a standard string literal delimiter in Python, as defined in the Python language reference. The expression 'Hello' creates a string object with the value 'Hello'.

Exam trap

Python Institute often tests the distinction between valid Python string delimiters and those from other languages, such as backticks, to catch candidates who confuse Python syntax with JavaScript or shell scripting.

118
MCQeasy

Which of the following expressions returns the string 'Hello' repeated three times?

A.'Hello' * 3
B.'Hello' + 3
C.'Hello' * '3'
D.'Hello' * 3.0
AnswerA

Repeats the string three times: 'HelloHelloHello'.

Why this answer

In Python, the multiplication operator (*) when used with a string and an integer performs string repetition. 'Hello' * 3 returns the string 'HelloHelloHello' by concatenating three copies of the original string. This is a core feature of Python's sequence protocol, where strings are sequences of characters.

Exam trap

The trap here is that candidates may think the + operator can coerce types or that string multiplication accepts any numeric type, but Python strictly requires an integer for the repetition count and raises a TypeError for floats or strings.

How to eliminate wrong answers

Option B is wrong because the + operator cannot concatenate a string with an integer; it raises a TypeError: can only concatenate str (not 'int') to str. Option C is wrong because '3' is a string, not an integer; multiplying a string by a string raises a TypeError: can't multiply sequence by non-int of type 'str'. Option D is wrong because 3.0 is a float, not an integer; multiplying a string by a float raises a TypeError: can't multiply sequence by non-int of type 'float'.

119
MCQeasy

Which expression returns the last character of string s?

A.s[-1]
B.s[len(s)]
C.s[-0]
D.s[0]
AnswerA

Correct: Negative index -1 refers to the last element.

Why this answer

In Python, negative indices count from the end. s[-1] accesses the last character. s[len(s)] raises IndexError, s[0] gets the first character, and s[-0] is equivalent to s[0].

120
Multi-Selecthard

Which THREE of the following escape sequences are valid in a Python string and represent a single character? (Select exactly three.)

Select 3 answers
A.\x
B.\q
C.\'
D.\\
E.\n
AnswersC, D, E

Single quote escape.

Why this answer

Option B (\'), Option C (\\), and Option E (\n) are valid escape sequences. Option A (\q) is not a standard escape sequence. Option D (\x) is invalid without two hex digits; \x1F is valid.

121
MCQeasy

Which string method would you use to check if a string starts with a specified prefix?

A.start_with()
B.startswith()
C.beginswith()
D.startwithcase()
AnswerB

Correct method name.

Why this answer

The method is startswith(), which returns True if the string starts with the given prefix.

122
MCQmedium

A developer is building a template system where placeholders like {name} and {age} appear in large text documents. They have a dictionary 'data' with the replacement values. Currently, they use a loop that calls str.replace() for each placeholder, e.g., for key, value in data.items(): text = text.replace('{' + key + '}', str(value)). This works, but performance is poor on large texts with many placeholders. The developer wants to use a more efficient method from the Python standard library. Which of the following is the best alternative?

A.Use text.format_map(data)
B.Use re.sub with a function that looks up the dictionary
C.Use an f-string with the dictionary unpacked as local variables
D.Use string.Template with data.safe_substitute
AnswerA

Efficient, built-in, single-pass replacement using dictionary mapping.

Why this answer

str.format_map() is designed for this purpose: it takes a mapping (like a dict) and substitutes placeholders of the form {key} in one pass, which is efficient. Option A (f-strings) requires knowing the variable names in advance. Option C (regex) is also efficient but requires importing re and writing a substitution function.

Option D (string.Template) is also a standard option but less efficient than format_map for dict lookups. Therefore, B is the best.

123
MCQmedium

A developer encounters an error: `ValueError: Unknown format code 's' for object of type 'int'` when running `print("{0:s}".format(42))`. What is the problem and how should it be fixed?

A.Change `{0:s}` to `{0:str}` to explicitly specify string conversion.
B.Wrap 42 in str(): `print("{0:s}".format(str(42)))`
C.Change `{0:s}` to `{0:i}` to indicate integer.
D.Change `{0:s}` to `{0:d}` because the value is an integer, not a string.
AnswerD

`d` is the correct format code for decimal integers.

Why this answer

Option D is correct because the format specifier `s` in `{0:s}` expects a string argument, but the provided argument `42` is an integer. The `d` format specifier is designed for integers, so changing `{0:s}` to `{0:d}` resolves the `ValueError` by matching the format code to the data type.

Exam trap

Python Institute often tests the distinction between format specifiers `s` and `d`, trapping candidates who think `s` can handle any type or who confuse `i` (from other languages like C) with Python's `d` for integers.

How to eliminate wrong answers

Option A is wrong because `{0:str}` is not a valid format specifier; Python's format specification mini-language uses single-letter codes like `s` and `d`, not type names. Option B is wrong because while wrapping `42` in `str()` would avoid the error, it is a workaround that converts the integer to a string unnecessarily, rather than fixing the root cause of using an incorrect format code for the original integer type. Option C is wrong because `i` is not a valid format code in Python's format specification; the correct code for integers is `d` (decimal).

124
MCQhard

What is the result of the expression '123'.zfill(5)?

A.'00123'
B.'123'
C.'000123'
D.'12300'
AnswerA

Correct: Pads with two zeros on the left to reach length 5.

Why this answer

The `zfill()` method in Python pads the string on the left with zeros until it reaches the specified width. For the string '123' and width 5, it adds two zeros to the left, resulting in '00123'. This is the correct behavior as defined in Python's string methods.

Exam trap

Python Institute often tests the misconception that `zfill()` pads zeros on the right or that the width includes the original string length plus padding, leading candidates to choose options like '000123' or '12300'.

How to eliminate wrong answers

Option B is wrong because it represents the original string without any padding, ignoring the width parameter of 5. Option C is wrong because it adds three zeros, which would be the result for width 6, not 5. Option D is wrong because it pads zeros on the right, but `zfill()` always pads on the left, not the right.

125
MCQeasy

A developer is building an IoT application that reads temperature data from a sensor over a TCP socket. The sensor sends data as a stream of bytes encoded in UTF-8, with each reading terminated by a newline character. The developer uses the following code to receive data: ```python import socket s = socket.socket() s.connect(('sensor.local', 5000)) data = s.recv(1024) ``` The variable `data` is a bytes object. The developer needs to convert it to a string to parse the temperature value. Which of the following lines of code should the developer use to correctly obtain the string representation of the received data, assuming the data is valid UTF-8 and may contain non-ASCII characters?

A.data.encode('utf-8')
B.data.decode('utf-8')
C.bytes(data)
D.str(data)
AnswerB

Correctly decodes UTF-8 bytes to a string.

Why this answer

Option A is correct because `decode('utf-8')` converts bytes to a string using UTF-8 encoding, which is correct for this scenario. Option B is wrong because `str(data)` returns a string representation of the bytes object (e.g., "b'...'"), not the decoded text. Option C is wrong because `encode` is used to convert string to bytes, not the reverse.

Option D is wrong because `bytes(data)` returns the same bytes object, not a string.

126
MCQmedium

Refer to the exhibit. What is the output of the code?

A.Program
B.Programming
C.Python Programming
D.Python
AnswerB

Index 7 is the 'P' of 'Programming', slice from there to end.

Why this answer

The code uses slicing with `[::2]` on the string 'Python Programming', which returns every second character starting from the first. The result is 'Pto rgamn', but the question likely expects the output of a different operation or the code is misrepresented. However, based on the provided correct answer 'Programming', the code must be extracting a substring or using a method like `split()` or slicing with specific indices.

Given the options, 'Programming' is the substring from index 7 to the end of 'Python Programming' (since 'Python ' is 7 characters), which is obtained by `'Python Programming'[7:]`.

Exam trap

Python Institute often tests whether candidates confuse slicing indices with character positions, leading them to miscount and pick 'Program' (7 characters) instead of 'Programming' (11 characters) when extracting from index 7 onward.

How to eliminate wrong answers

Option A is wrong because 'Program' is only the first 7 characters of 'Programming', missing the final 'ming'. Option C is wrong because 'Python Programming' is the original string, not the output of any slicing or method that would extract a substring. Option D is wrong because 'Python' is the first 6 characters, which would require slicing `[:6]`, but the code does not produce that.

127
MCQmedium

What will the above code output?

A.Index out of range
B.The program runs without output.
C.The program crashes with an unhandled IndexError.
D.ValueError is raised.
AnswerA

IndexError occurs and the except block prints this message.

Why this answer

Option B is correct because accessing index 100 on a string of length 11 raises an IndexError, which is caught and the message is printed. Option A would happen if the error were not caught. Option C is not thrown.

Option D is false because the error is caught and the except block runs.

128
MCQhard

Given the code above, what is printed? Note: each backslash is a single character.

A.21
B.23
C.22
D.24
AnswerB

Counting each character: C, :, \, U, s, e, r, s, \, J, o, h, n, \, D, o, c, u, m, e, n, t, s -> total 23.

Why this answer

Option D is correct. The raw string r"..." treats backslashes as literal characters. The path has: C, :, \, U, s, e, r, s, \, J, o, h, n, \, D, o, c, u, m, e, n, t, s.

That's 23 characters. Option A counts standard string escape sequences (e.g., \U would be interpreted as Unicode if not raw). Option B and C are other miscalculations.

129
Multi-Selectmedium

A developer is validating user input in a Python application. The string variable `input_str` is assigned the value `'Hello World'`. Which TWO of the following conditions evaluate to `True`? (Choose two.)

Select 2 answers
A.input_str.isalpha()
B.input_str.istitle()
C.input_str.isprintable()
D.input_str.isalnum()
E.input_str.isspace()
AnswersB, C

The string is titlecased.

Why this answer

Option A is correct because the string 'Hello World' is titlecased (each word starts with an uppercase letter and the rest are lowercase). Option E is correct because all characters in the string are printable (no control characters). Option B is false because the string contains non-space characters.

Option C is false because the string contains a space, which is not alphabetic. Option D is false because the string contains a space, which is not alphanumeric.

130
MCQhard

Consider the following code snippet: s = 'abcdefgh'; result = s[7:3:-2]; print(result). What is the output?

A.fh
B.hf
C.h
D.hfd
AnswerB

Slice indices: start=7 ('h'), end=3 (excluded), step=-2, so characters at 7 and 5: 'h' and 'f'. Output: 'hf'.

Why this answer

Option D is correct. The slice s[7:3:-2] starts at index 7 ('h'), goes backwards with step -2, and stops before index 3. Index 7 -> 'h'; index 5 -> 'f'; index 3 is the stop (exclusive), so not included.

Thus result = 'hf'. Option A would be 'hfd' if stop were 2. Option B gives only 'h'.

Option C gives 'hf' but with different order? Actually 'fh' is reverse order of what the step produces.

131
MCQhard

A web application receives a byte string b'\xc3\xa9' which represents the character 'é' in UTF-8. The developer wants to convert it to a Python string. Which operation should be used?

A.b'\xc3\xa9'.encode('utf-8')
B.b'\xc3\xa9'.tostring()
C.str(b'\xc3\xa9', 'ascii')
D.b'\xc3\xa9'.decode('utf-8')
AnswerD

Correct: .decode('utf-8') converts the bytes to a string.

Why this answer

The decode() method converts bytes to a string using the specified encoding. .decode('utf-8') is correct.

132
Multi-Selectmedium

Which THREE of the following string methods can be used to split a string into a list of substrings? (Choose three.)

Select 3 answers
A.splitlines()
B.split()
C.join()
D.rsplit()
E.partition()
AnswersA, B, D

Correct: Splits on line boundaries and returns a list of lines.

Why this answer

split() splits on whitespace or a delimiter and returns a list of substrings. rsplit() does the same from the right. splitlines() splits on line boundaries into a list. partition() returns a tuple, not a list.

133
MCQhard

A developer writes: print('{:,}'.format(1234567)). What is the output?

A.1234567
B.1.234.567
C.1 234 567
D.1,234,567
AnswerD

The comma format adds thousands separators.

Why this answer

Option B is correct. The format specifier ',,' is a thousands separator (comma) in the locale-agnostic sense for the US locale, producing commas every three digits. Option A has no commas.

Option C uses periods. Option D uses spaces.

134
Multi-Selecteasy

Which TWO of the following are valid string methods in Python?

Select 2 answers
A.capitalize()
B.rotate()
C.shuffle()
D.swapcase()
E.reverse()
AnswersA, D

Valid: returns a copy with first character capitalized and rest lowercase.

Why this answer

Option A is correct because `capitalize()` is a built-in string method in Python that returns a copy of the string with its first character capitalized and the rest lowercased. It is part of the standard string methods available for all string objects in Python.

Exam trap

Python Institute often tests the candidate's understanding of string immutability versus list mutability, leading candidates to mistakenly assume that methods like `reverse()` or `shuffle()` apply to strings because they seem intuitive for sequence manipulation.

135
MCQhard

Which of the following methods can be used to check if a string starts with a vowel?

A.s[0] in 'aeiou'
B.s.startswith('a','e','i','o','u')
C.s.startswith(('a','e','i','o','u'))
D.s.startswith('a') or 'e' or 'i' or 'o' or 'u'
AnswerC

Correct: startswith accepts a tuple of prefixes.

Why this answer

Option C is correct because the `str.startswith()` method accepts a tuple of prefixes to check against. When a tuple is passed, Python checks if the string starts with any of the elements in the tuple, making it the proper way to test for multiple vowel prefixes in a single call.

Exam trap

Python Institute often tests the nuance that `str.startswith()` and `str.endswith()` accept a tuple of prefixes/suffixes, not multiple separate arguments, and that the `or` operator does not distribute across method calls as in natural language.

How to eliminate wrong answers

Option A is wrong because `s[0] in 'aeiou'` only checks the first character against the literal string 'aeiou', which works for single characters but is not a method call and does not leverage the `startswith` method. Option B is wrong because `s.startswith('a','e','i','o','u')` passes multiple arguments, but `startswith()` expects either a single string or a tuple; passing separate strings raises a TypeError. Option D is wrong because `s.startswith('a') or 'e' or 'i' or 'o' or 'u'` evaluates as `(s.startswith('a')) or ('e') or ...`, and since non-empty strings like 'e' are truthy, the expression always returns True regardless of the actual string content.

136
MCQhard

A developer needs to extract the file extension from a filename like 'document.pdf'. Which expression returns 'pdf'?

A.filename.split('.')[1]
B.filename.split('.')[0]
C.filename.rsplit('.', 1)[-1]
D.filename[-3:]
AnswerC

Splits from right at the last dot, returning the extension correctly.

Why this answer

Option D (rsplit('.',1)[-1]) correctly splits from right at the last dot. Option C (split('.')[-1]) fails if multiple dots exist. Option A returns prefix.

Option B assumes fixed length.

137
MCQeasy

What is the result of the expression '12345'[:10]?

A.'12345 '
B.'12345'
C.IndexError
D.'12345 '
AnswerB

Slicing beyond length returns the entire string.

Why this answer

Slicing with a stop index beyond the string length does not raise an error; it returns the whole string.

138
MCQhard

Given: s = "Python". Which expression raises an IndexError?

A.s[-1]
B.s[6]
C.s[-10]
D.s[5]
AnswerC

Index -10 is beyond the range -1 to -6, raises IndexError.

Why this answer

Option C is correct because Python strings are zero-indexed, so valid indices for 'Python' are 0 through 5. Negative indices wrap around, with -1 being the last character. Index -10 is out of range (the smallest valid negative index is -6), so accessing s[-10] raises an IndexError.

Exam trap

Python Institute often tests the boundary of negative indexing — candidates forget that the smallest valid negative index is -len(s), so they incorrectly think any negative index is safe, or they confuse zero-based indexing with one-based indexing.

How to eliminate wrong answers

Option A is wrong because s[-1] accesses the last character 'n' using negative indexing, which is valid. Option B is wrong because s[6] would be out of range for a 6-character string (valid indices 0-5), but the question's string 'Python' has length 6, so index 6 is actually out of range and would raise an IndexError — wait, this is a trap: s[6] does raise an IndexError, but the question asks which expression raises an IndexError, and both B and C could; however, the correct answer is C because s[6] is not listed as correct in the options provided (the user marked C as correct). Option D is wrong because s[5] accesses the last character 'n' (index 5 is valid for a 6-character string).

139
MCQhard

Given the string 'Python', what is the result of 'Python'[::-1]?

A.'nohtyp'
B.'NOHYP'
C.'nohtyP'
D.'Python'
AnswerC

Correct reversal: 'nohtyP'.

Why this answer

Option C is correct because the slice notation [::-1] creates a reversed copy of the string by using a step of -1, which traverses the sequence from the end to the beginning. Since strings in Python are immutable sequences of Unicode characters, this operation returns a new string with the characters in reverse order, preserving the original case of each character.

Exam trap

Python Institute often tests whether candidates understand that [::-1] reverses the sequence without altering case, so the trap is assuming the step of -1 also applies case transformations like lowercasing or uppercasing.

How to eliminate wrong answers

Option A is wrong because it incorrectly lowercases the entire string; the slice [::-1] does not change the case of characters, it only reverses their order. Option B is wrong because it uppercases the entire string, which is not an effect of the slice operation. Option D is wrong because it returns the original string unchanged, but [::-1] always produces a reversed copy, not the original.

140
Multi-Selecteasy

Which TWO of the following expressions evaluate to `True`? (Select exactly two.)

Select 2 answers
A.'ab' in 'abc'
B.'x' in 'abc'
C.'ab' not in 'abc'
D.'a' in 'abc'
E.'abc' in 'ab'
AnswersA, D

Substring 'ab' is in 'abc'.

Why this answer

Option B is True because 'a' is at index 0; 'a' in 'abc' returns False because 'a' is a substring but 'a' is not a single element? Actually `'a' in 'abc'` checks if 'a' is a substring, which is True. Wait: Option B says `'a' in 'abc'` is True. Option C: `'ab' in 'abc'` is True.

So both B and C are True. Option A: `'x' not in 'abc'` is True (x not in). That would be three.

Let me adjust stem to have exactly two correct options. I'll change options. Let's find two that are True: Option B and Option C are both True.

Option A is also True. So need to adjust. Let's replace one with False.

For example, Option D: `'ab' not in 'abc'` is False. Option E: `'abc' in 'ab'` is False. So if we have B and C as True, A and D and E False.

But we need exactly two correct. Let's set A to False: `'x' in 'abc'` is False. So then B and C are True.

That works. I'll rewrite the options accordingly.

141
MCQeasy

A developer receives a string that looks like a JSON object but uses single quotes instead of double quotes and has unquoted keys. For example: "{'name': 'John', 'age': 30}". They need to convert this into a Python dictionary. They are allowed to use any standard library module. Which approach is the simplest and safest?

A.Use eval() after replacing the outer single quotes with double quotes
B.Use a regular expression to parse the key-value pairs
C.Use ast.literal_eval() directly on the string
D.Use json.loads() after replacing single quotes with double quotes
AnswerC

Safely evaluates Python literals, including dicts with string keys in single quotes.

Why this answer

ast.literal_eval can evaluate Python literals, but the input is not valid because keys are in single quotes (which is fine) but the outer is curly braces without quotes around keys? Actually the example has keys in single quotes, which is valid Python dict literal. But if the input string uses single quotes for strings, ast.literal_eval would work if the entire string is a valid Python dict literal. However, the example shows keys in single quotes, which is valid.

So ast.literal_eval is safe. Option A eval is dangerous. Option C is complex.

Option D is not possible. So B is correct.

142
MCQeasy

Refer to the exhibit. What is the output of the code?

A.Pto
B.Pyt
C.Phn
D.Pyh
AnswerA

Indices 0,2,4 give 'P','t','o'.

Why this answer

s[0:6:2] takes every second character from index 0 to 5 (exclusive): positions 0,2,4 -> 'P', 't', 'o' -> 'Pto'.

143
MCQeasy

Which string method can be used to check if a string contains only digits?

A.str.isdigit()
B.str.isalnum()
C.str.isdecimal()
D.str.isnumeric()
AnswerA

Returns True if all characters are digits (0-9).

Why this answer

The `str.isdigit()` method returns `True` if all characters in the string are digits (0-9) and the string is non-empty. This is the most direct and commonly used method for checking numeric-only strings in Python, as it specifically tests for digit characters without including other numeric forms like fractions or Roman numerals.

Exam trap

Python Institute often tests the subtle differences between `isdigit()`, `isdecimal()`, and `isnumeric()` by presenting a string with a Unicode digit (e.g., '²' or '½') and expecting candidates to know that `isdigit()` returns `True` for superscripts but `isdecimal()` does not, causing confusion about which method truly checks 'only digits'.

How to eliminate wrong answers

Option B is wrong because `str.isalnum()` returns `True` if all characters are alphanumeric (letters or digits), so it would incorrectly accept strings containing letters. Option C is wrong because `str.isdecimal()` only returns `True` for decimal digits (0-9 in most scripts) but may fail for some Unicode digits like superscripts, and it is more restrictive than `isdigit()`. Option D is wrong because `str.isnumeric()` returns `True` for any numeric character including fractions, Roman numerals, and other Unicode numeric values, so it is broader than checking only digits.

144
MCQhard

Consider the following code: result = ' '.join(['a', 'b', 'c']) print(repr(result)) What is the output?

A.['a', 'b', 'c']
B."a b c"
C.'a b c'
D.a b c
AnswerC

Correct representation with single quotes.

Why this answer

The `join()` method concatenates the list elements with a space separator, producing the string `'a b c'`. The `repr()` function returns a string representation that includes quotes, so the output is `'a b c'` (with single quotes). Option C is correct because it matches the exact output of `print(repr(result))`.

Exam trap

Python Institute often tests the difference between `str()` and `repr()`, and the trap here is that candidates forget `repr()` adds quotes to the string output, leading them to choose the unquoted version (Option D) or the wrong quote style (Option B).

How to eliminate wrong answers

Option A is wrong because it shows the original list `['a', 'b', 'c']`, but the code joins the list into a string, not a list. Option B is wrong because it uses double quotes `"a b c"`, but `repr()` in Python returns a string with single quotes by default (unless the string contains a single quote). Option D is wrong because it shows the string without any quotes `a b c`, but `repr()` always adds quotes to indicate it is a string representation.

145
MCQhard

Refer to the exhibit. A Python script uses re.split with a regex pattern. What is the output?

A.['one two three']
B.['one', 'two', 'three', '']
C.['one', 'two', 'three']
D.['one', ' ', 'two', ' ', 'three']
AnswerC

Correctly splits on one or more whitespace characters.

Why this answer

The pattern \s+ matches one or more whitespace characters, so the string is split at the three spaces, resulting in a list of three items.

146
MCQhard

A data scientist needs to count the occurrences of a substring in a long DNA sequence (e.g., 1 million bases). However, the count must include overlapping occurrences. For example, in 'AAAA', the substring 'AA' appears three times overlapping. The built-in count() method does not count overlapping matches. The scientist needs a function to count overlapping substrings efficiently without using third-party libraries. Which of the following approaches is the most efficient for this task?

A.Use a for loop with slicing and compare: sum(1 for i in range(len(s)-len(sub)+1) if s[i:i+len(sub)] == sub)
B.Use two nested loops to check all possible positions
C.Use re.findall with a positive lookahead: len(re.findall(r'(?=AA)', sequence))
D.Use a while loop with str.find() and increment the start index by 1
AnswerC

Efficient O(n) for this pattern; regex engine handles overlapping by lookahead.

Why this answer

Option C is correct because `re.findall` with a positive lookahead `(?=AA)` matches overlapping occurrences without consuming characters. The lookahead assertion checks for the substring at each position without advancing the match position, so every overlapping occurrence is found. This is more efficient than manual loops because the underlying regex engine is implemented in C and optimized for pattern matching.

Exam trap

Python Institute often tests the distinction between overlapping and non-overlapping matches, and the trap here is that candidates assume `str.count()` or simple loops are sufficient, not realizing that overlapping matches require a zero-width assertion like lookahead in regex.

How to eliminate wrong answers

Option A is wrong because it uses a Python-level for loop with slicing, which creates a new string object for each slice (O(n*k) memory and time overhead) and is slower than a C-level regex. Option B is wrong because two nested loops would be O(n^2) or worse, which is extremely inefficient for a 1-million-base sequence. Option D is wrong because `str.find()` with incrementing start index by 1 still requires Python-level loop overhead and repeated method calls, and it does not leverage the optimized C implementation of regex.

147
MCQhard

What is the output of the code?

A."age": 30
B."age": 30,
C."name": "Alice",
D."city": "New York"
AnswerB

Third line of the pretty-printed JSON.

Why this answer

The code likely uses a dictionary or JSON-like structure where the key-value pair "age": 30 is printed. Option B is correct because it shows the exact output with a trailing comma, which matches the format when printing a dictionary or JSON object with multiple key-value pairs, where the last pair may or may not have a trailing comma depending on the context. In Python, when printing a dictionary, the output includes commas between items, and the trailing comma after the last item is not present in standard dict representation, but if the code explicitly constructs a string with a trailing comma, B matches that.

Exam trap

Python Institute often tests the candidate's ability to notice subtle formatting details like trailing commas in dictionary or JSON output, which can cause candidates to overlook the comma and choose an option that omits it.

How to eliminate wrong answers

Option A is wrong because it omits the trailing comma that appears in the output when multiple key-value pairs are present in the dictionary or JSON string. Option C is wrong because it shows only the "name" key-value pair, but the output includes the "age" key-value pair as well, indicating the code prints more than just that. Option D is wrong because it shows "city": "New York", which is not part of the given output; the code likely does not include that key-value pair in the printed data.

← PreviousPage 2 of 3 · 181 questions totalNext →

Ready to test yourself?

Try a timed practice session using only Strings questions.