Courseiva

CCNA Strings Questions

75 of 151 questions · Page 2/3 · Strings topic · Answers revealed

76
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

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.

77
Multi-Selectmedium

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

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

This is correct because Python implicitly concatenates adjacent string literals at compile time. The expression ('Line1\n' 'Line2') produces the single string 'Line1\nLine2', where \n is a single escape character representing a line break. When printed, the result appears on two lines, so it is a valid multiline string. The parentheses are not required but help break long lines for readability.

Why this answer

Options A, B, and C are all valid ways to create a multiline string in Python. Option A uses implicit string concatenation within parentheses; the `\n` escape sequence inserts a newline, resulting in a multiline string. Option B uses triple double quotes to span multiple lines physically, preserving line breaks.

Option C uses triple single quotes, which work identically to triple double quotes for multiline strings. Option D uses a backslash for line continuation, which does not insert a newline into the string—it just continues the literal on the next line, so the result is a single-line string without a newline. Option E causes a syntax error because a single-quoted string literal cannot span multiple lines without a continuation character.

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.

78
MCQhard

Refer to the exhibit. What is the output?

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

This is the correct result after executing both operations in sequence: first, replace("Hello", "Hi") changes the string to "Hi, World!"; second, upper() converts every alphabetic character to uppercase, producing "HI, WORLD!". The order of the chain matters—the replacement happens before case conversion, so the greeting becomes "HI" instead of "HELLO", matching the exhibited output exactly.

Why this answer

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

79
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

This is correct because it explicitly tests each character against the exact set of valid hexadecimal digits, '0123456789abcdefABCDEF', using the all() function with a generator expression. Every character in s must be a member of that set for the expression to evaluate to True. One subtlety is that all() returns True for an empty string, so if an empty input should be considered invalid, an additional length check is needed.

Why this answer

It explicitly checks each character in the string against the set of valid hexadecimal digits (0-9, a-f, A-F) using the `all()` function. This ensures that every character is a hex digit, which is the precise requirement for a string to contain only hexadecimal digits.

Exam trap

The PCAP exam often tests the misconception that `isalnum()` or `isdigit()` combined with `isalpha()` can validate hex digits, but they fail because they do not restrict letters to the a-f/A-F range and may accept non-ASCII characters.

How to eliminate wrong answers

Option A is wrong because `s.isdigit()` returns True only for decimal digits (0-9), and `s.isalpha()` returns True only for alphabetic characters; combining them with `or` would accept strings that are entirely digits or entirely letters, but not necessarily hex digits (e.g., 'g' would pass isalpha but is not a hex digit). Option B is wrong because `s.isnumeric()` returns True for any numeric characters including Unicode numerals (e.g., ², ½) and decimal digits, but it does not accept letters a-f/A-F, so it would reject valid hex strings like '1a'. Option C is wrong because `s.isalnum()` returns True if all characters are alphanumeric (letters or digits), but it does not restrict letters to a-f/A-F (e.g., 'g' would pass), and `s.islower()` would reject strings containing uppercase hex letters like 'A', making it too restrictive.

80
MCQeasy

A developer is formatting a log message and wants to ensure that a string variable `name` is centered within a field of width 20, padded with asterisks (`*`) on both sides. For example, if `name = "Alice"`, the result should be `*******Alice********` (7 asterisks on the left, 8 on the right). Which method call achieves this?

A.name.rjust(20, '*')
B.name.ljust(20, '*')
C.name.center(20, '*')
D.name.zfill(20)
AnswerC

The str.center(width, fillchar) method returns a new string of length width, with the original string centered and padded with the specified fill character. For 'Alice' and width 20, the total padding is 15 characters. Python puts the extra padding on the right when the padding is odd, resulting in 7 asterisks on the left and 8 on the right, exactly as required.

Why this answer

To center a string within a field and pad with a specific character, the str.center() method is used. It takes the desired width and an optional fill character. When the total padding is odd, Python places the extra character on the right, matching the example.

The other methods either left-justify, right-justify, or pad with zeros, none of which produce a centered result with asterisks on both sides.

Exam trap

The trap here is mixing up the justification methods and forgetting that center() places extra padding on the right when the total padding is odd.

81
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

s[1::2] begins at index 1 (the first digit character '1') and then takes every second character thereafter, with no explicit stop so it runs to the end of the string. Indices 1, 3, and 5 correspond to '1', '2', and '3', respectively, so the result is exactly '123'. This is the correct expression because it isolates the digits that are positioned at odd indices.

Why this answer

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.

82
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() returns a copy with leading whitespace characters removed, leaving trailing and internal whitespace untouched. This matches the stem's constraint precisely, since only leading spaces, tabs and newlines must be stripped, and lstrip() is a built-in string method requiring no import.

Why this answer

The `lstrip()` method removes all leading whitespace characters (spaces, tabs, newlines) from the left side of a string. `strip()` removes leading and trailing whitespace, so it also satisfies the requirement of removing leading whitespace. Both are built-in string methods in Python.

Exam trap

Candidates often confuse `rstrip()` with removing leading whitespace because of the 'r' prefix, or incorrectly assume `trim()` or `clean()` are valid Python methods.

83
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

s.strip() correctly removes whitespace from both the beginning and the end of the string. For example, ' hello '.strip() returns 'hello', eliminating the leading and trailing spaces. Because it precisely matches the requirement, and because strings are immutable, it returns a new stripped string rather than modifying the original.

Why this answer

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.

84
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. The format specifier `.2f` is a dot (precision marker) followed by `2` (the number of digits) and the fixed-point type `f`. This tells Python to render `value` as a float rounded to exactly two decimal places, so 3.14159 becomes `3.14`. This is the official way to force a fixed number of digits after the decimal point in f-string formatting.

Why this answer

Uses the correct f-string format specifier `:.2f`, where `f` stands for fixed-point notation and `.2` specifies two decimal places. This is the standard Python syntax for formatting a floating-point number to two decimal places within an f-string.

Exam trap

The Python Institute often tests the distinction between the width specifier (e.g., `:2f`) and the precision specifier (e.g., `:.2f`), so candidates mistakenly choose Option D thinking `:2f` means two decimal places, when it actually sets a minimum field width of 2 characters.

How to eliminate wrong answers

Option B is wrong because `:.2` omits the `f` type specifier, which means Python will apply the general format type (default `g`) and may not produce exactly two decimal places (e.g., it could use scientific notation or drop trailing zeros). Option C is wrong because `%` is not a valid format specifier component; the correct syntax uses a colon `:` after the expression, not a percent sign. Option D is wrong because `:2f` lacks the decimal point before the `2`, so it specifies a minimum width of 2 characters rather than two decimal places, which can lead to incorrect formatting (e.g., `f"{3.14159:2f}"` outputs `"3.141590"` with six decimal places, not two).

85
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

startswith() is the correct and idiomatic Python string method for checking whether a string begins with a given prefix. It accepts a single string, a tuple of strings, or optional start and end indices, returning True if the string starts with the specified prefix and False otherwise. Its behavior is case-sensitive, and it is implemented in C for efficiency, making it the standard tool for this common validation task. This is the only method among the options that actually exists and performs the required check.

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

86
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

startswith() is a boolean predicate that returns True exactly when the string's prefix matches the supplied prefix, optionally constraining the check with the start and end index arguments. It never modifies the original string and its only meaningful return values are True and False, making it one of the two methods that answer the question correctly.

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.

87
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

The correct implementation first trims surrounding whitespace with s.strip(), then removes any leading/trailing punctuation characters via s.strip('.,!?;:') — a subtle but important order, because punctuation attached after spaces (e.g., " hello! ") is only exposed for removal after the outer whitespace is gone. Lowercasing follows, and finally re.sub(r'\s+', ' ', s) collapses any runs of internal whitespace (tabs, newlines, multiple spaces) into a single space. This sequence yields a fully canonical form: " Hello, World!! " becomes "hello, world". It deliberately handles each normalization dimension independently, making the result predictable for exact-match comparisons.

Why this answer

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.

88
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

s.split(',') is correct because str.split() with a specified separator splits the string at every occurrence of that separator and returns a list of the substrings in between, with the separator removed. For the string 'apple,banana,orange', this yields ['apple', 'banana', 'orange'], exactly the three separate fruits the programmer wants. This is the standard built-in method for turning a delimited string into a list of parts.

Why this answer

`s.split(',')` splits the string `'apple,banana,orange'` at each comma delimiter, returning a list of substrings: `['apple', 'banana', 'orange']`. This method is designed to break a string into a list based on a specified separator, making it the exact tool for this task.

Exam trap

The PCAP exam often tests the confusion between `split()` and `partition()` — candidates mistakenly think `partition()` returns a list of all parts, but it only splits at the first occurrence and returns a tuple, not a list of all comma-separated items.

How to eliminate wrong answers

Option A is wrong because `s.splitlines()` splits a string at line boundaries (e.g., newline characters), not at commas, so it would return a single-element list `['apple,banana,orange']` if no newlines are present. Option B is wrong because `s.partition(',')` returns a tuple of three elements: the part before the first comma, the comma itself, and the rest after it (e.g., `('apple', ',', 'banana,orange')`), not a list of all comma-separated items. Option C is wrong because `s.join(',')` is a string method that concatenates an iterable of strings with the separator, but calling it on a string like `s` (which is not an iterable of strings) raises a `TypeError`; it is the inverse of `split()` and cannot produce a list from a single string.

89
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

This is the correct slice. Python's slice s[start:stop] includes characters from start up to, but not including, stop; therefore s[7:18] returns the characters at indices 7 through 17, which spell exactly 'programming'. The start index 7 points to the first letter 'p', and the exclusive stop index 18 excludes the space that immediately follows the word, ensuring a precise extraction.

Why this answer

Python uses zero-based indexing. The word 'programming' starts at index 7 (the character 'p' in 'programming') and ends at index 17 (the character 'g'), but slicing is exclusive of the end index, so s[7:18] extracts characters from index 7 up to but not including index 18, which gives 'programming'.

Exam trap

The PCAP exam often tests the off-by-one error in slicing, where candidates forget that the stop index is exclusive, leading them to choose options that include an extra character or miss the correct substring.

How to eliminate wrong answers

Option A is wrong because s[6:18] starts at index 6, which is the space before 'programming', resulting in ' programming' (with a leading space). Option C is wrong because s[7:19] ends at index 19, which is the space after 'programming', resulting in 'programming ' (with a trailing space). Option D is wrong because s[6:19] starts at index 6 (space) and ends at index 19 (space after 'programming'), producing ' programming ' (with leading and trailing spaces).

90
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, C, D

This invokes re.sub with the pattern [0-9], a character class that matches exactly one character from the range '0' through '9'. Each matched digit is replaced independently with 'X', so the entire message is scanned and every digit becomes an X. Because re.sub processes the whole string and replaces all non-overlapping matches, this correctly sanitizes all ASCII digits in the message.

Why this answer

Options B, C, and D all correctly replace all digits in the message with 'X'. Option B uses `re.sub()` with a regex character class to match any digit. Option C uses `str.translate()` with a mapping from each digit to 'X', which works because the mapping explicitly covers all digits.

Option D uses a list comprehension with `isdigit()` to conditionally replace digits. Option A is incorrect because `str.replace()` does not interpret character ranges; it would look for the literal string '0-9'. Therefore, three correct approaches exist.

Exam trap

Candidates may assume only `re.sub()` is correct, but `str.translate()` with explicit mapping and list comprehension with `isdigit()` also achieve the same result. The exam may expect recognition that multiple Python methods can accomplish the same task.

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.

91
MCQeasy

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

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

Calling lower() on the string 'aBc' returns a new string where every cased character has been converted to its lowercase form: the leading 'a' is already lowercase and stays 'a', while the uppercase 'B' becomes 'b'. The result is therefore exactly 'abc' — a three-character string with no uppercase letters remaining. This is the documented behavior of str.lower() in Python.

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

92
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

The negative lookbehind (?<!big) is a zero-width assertion that succeeds only when the characters immediately before the current position are not 'big'; if they are, the match attempt at that location fails. As a result, every 'cat' that is not part of 'bigcat' is replaced with 'dog', while 'bigcat' stays exactly as is. This correctly replaces all occurrences of 'cat' except those preceded by 'big'.

Why this answer

Uses a negative lookbehind assertion `(?<!big)` to match 'cat' only when it is NOT preceded by 'big'. This ensures that 'bigcat' remains unchanged while standalone 'cat' is replaced with 'dog'. The `re.sub` function then substitutes all such matches in the string.

Exam trap

The PCAP exam often tests the distinction between positive and negative lookbehinds, and the trap here is that candidates confuse `(?<=...)` (match if preceded by) with `(?<!...)` (match if NOT preceded by), leading them to choose Option C instead of D.

How to eliminate wrong answers

Option A is wrong because it matches the literal string 'bigcat' and replaces the entire sequence with 'dog', which would turn 'bigcat' into 'dog' instead of leaving it unchanged. Option B is wrong because it replaces every occurrence of 'cat' regardless of context, including those preceded by 'big'. Option C is wrong because it uses a positive lookbehind `(?<=big)` which matches 'cat' only when it IS preceded by 'big', the exact opposite of the requirement.

93
MCQeasy

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

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

The expression 'hello'.count('l') correctly returns 2, the total number of non-overlapping occurrences of the character 'l' in the string. Python's str.count() method counts each match from left to right, and since 'hello' consists of 'h', 'e', 'l', 'l', 'o', it finds an 'l' at position 2 and another at position 3 (0-based). Therefore, the output is exactly 2.

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.

94
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

The statement s[0] = 'J' raises a TypeError because assignment to an indexed position attempts to modify the contents of an existing str object, and immutable objects do not support item assignment. The interpreter explicitly forbids this operation, which is the most direct and unambiguous demonstration of string immutability.

Why this answer

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.

95
MCQmedium

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

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

Indexing 'python' from zero gives p=0, y=1, t=2, h=3, o=4, n=5; the two-character substring 'th' begins at offset 2, where 't' resides and is followed immediately by 'h'. Python's str.find returns the lowest zero-based index at which the substring starts, so 'python'.find('th') evaluates to exactly 2. This is the correct result.

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

96
Drag & Dropmedium

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

Drag or tap steps into the slots.

Steps
Order
1Step 1
2Step 2
3Step 3
4Step 4

Why this order

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

97
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 all leading and trailing whitespace characters — such as spaces, tabs, and newlines — and returns a new string with those characters removed. For "hello world", there are no surrounding whitespace characters, so it returns the exact same string unchanged. It leaves any internal whitespace intact, which is the desired behavior for trimming a string. This method is the standard and correct way to clean up whitespace at both ends of a string.

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

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

99
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

The f-string (formatted string literal) is the recommended formatting method in Python 3.6+ because it allows expressions to be embedded directly inside braces exactly where the value belongs in the text. It is concise, readable, and evaluated at runtime, so it can call functions, index collections, or access attributes without extra method calls. PEP 498 and the official Python documentation endorse f-strings as the preferred form for new code.

Why this answer

PEP 498 introduced f-strings (formatted string literals) as the recommended approach for string formatting in Python 3.6+. They are concise, readable, and evaluated at runtime, allowing direct embedding of expressions. This aligns with the 'Pythonic' principle of simplicity and is the preferred style for new code according to the official Python documentation.

Exam trap

The PCAP exam often tests the distinction between 'most Pythonic' and 'works correctly' — candidates may pick .format() because it is familiar, but PEP 498 explicitly recommends f-strings for new code, making them the correct answer in a PCAP context.

How to eliminate wrong answers

Option A is wrong because %-formatting is the old-style C-like printf approach, which is less readable and not recommended for new code per PEP 498. Option B is wrong because .format() is more verbose and less direct than f-strings, though still valid; it is not the most Pythonic for simple variable interpolation. Option C is wrong because string concatenation is inefficient (creates multiple intermediate strings) and less readable, violating Pythonic principles of clarity and simplicity.

100
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() with a translation table is correct because it replaces every character in a single C-level pass: each character's code point is looked up in the table and replaced with the designated string, or deleted if mapped to None, without constructing intermediate copies. The translation table is created once via str.maketrans() and reused for every line or chunk, so the total work is proportional to the file size rather than to the number of distinct replacements. This makes it the fastest built-in approach for bulk character-level substitutions in large text.

Why this answer

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

101
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

Strings in Python are immutable, so indexed assignment raises TypeError: 'str' object does not support item assignment. The statement s[0] = 'x' attempts in-place mutation of an existing str object, which the type forbids; the interpreter rejects it at runtime rather than silently creating a new string.

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.

102
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

The literal 'Hello' is a standard single-quoted string, which is a perfectly valid way to create a string in Python. It uses a matching pair of single quote characters as delimiters, enclosing the sequence of characters exactly as written. Functionally, single-quoted strings are equivalent to double-quoted strings, though consistency in quoting style is a common best practice.

Why this answer

In Python, valid string literals can be enclosed in single quotes, double quotes, triple single quotes, or triple double quotes. Formatted string literals (f-strings) are also valid. Option A is invalid because it uses mismatched quote characters: it opens with a single quote but closes with a double quote.

Option B uses consistent single quotes. Option C is an f-string. Option D uses backticks, which are not valid Python string delimiters.

Option E uses triple single quotes, which are valid for multi-line strings.

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.

103
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

In Python, the * operator, when applied to a string and an integer, performs sequence repetition. Because 3 is an int, 'Hello' * 3 creates a new string by joining three sequential copies of the original 'Hello', yielding exactly 'HelloHelloHello'. This is valid string repetition that works for any string and any non-negative integer, and it returns a single string object, not a tuple or list.

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

104
MCQeasy

Which expression returns the last character of string s?

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

Python supports negative indices that count from the end of a sequence. An index of -1 specifically refers to the last element, so s[-1] evaluates to the final character of s, regardless of the string's length. Internally, Python converts negative indices by adding len(s), yielding len(s)-1, which is always the final valid position.

Why this answer

Python uses zero-based indexing for strings, where negative indices count from the end. s[-1] directly accesses the last character of the string, as -1 refers to the final element in the sequence.

Exam trap

The PCAP exam often tests the misconception that negative indexing starts at -0 or that len(s) is a valid index, leading candidates to pick s[len(s)] or s[-0] when they forget that indices are zero-based and negative indices count from -1 for the last element.

How to eliminate wrong answers

Option B is wrong because s[len(s)] raises an IndexError: string index out of range, since valid indices for a string of length n are 0 to n-1. Option C is wrong because s[-0] is equivalent to s[0], which returns the first character, not the last. Option D is wrong because s[0] returns the first character of the string, not the last.

105
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

The backslash followed by a single quote (\') is a valid escape sequence in Python that represents a literal single quote character, allowing it to appear inside a single-quoted string without terminating the string. This sequence is interpreted as a single character by the Python parser.

Exam trap

The PCAP exam often tests the distinction between valid and invalid escape sequences, and the trap here is that candidates may assume any backslash-letter combination (like \q) is valid, or that \x alone is sufficient, when in fact only a fixed set of sequences are recognized and incomplete sequences cause a SyntaxError.

106
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

startswith() is the correct and documented Python string method for prefix detection. It returns True if the string begins with the specified prefix and False otherwise. It also accepts a tuple of prefixes to check multiple alternatives, and optional start and end parameters to limit the search range within the string.

Why this answer

The correct method to check if a string starts with a specified prefix in Python is `str.startswith()`. It returns `True` if the string begins with the given prefix, otherwise `False`. This method is part of the standard string methods in Python and is case-sensitive by default.

Exam trap

The PCAP exam often tests the exact method name spelling and punctuation, so the trap here is that candidates may confuse `startswith()` with the non-existent `start_with()` or `beginswith()` due to familiarity with other languages or naming conventions.

How to eliminate wrong answers

Option A is wrong because `start_with()` is not a valid Python string method; the correct method uses `startswith` without an underscore. Option C is wrong because `beginswith()` is not a Python string method; Python uses `startswith` for this functionality. Option D is wrong because `startwithcase()` does not exist; Python's `startswith` method does not have a case-insensitive variant built-in, though you can achieve case-insensitive behavior by converting both strings to the same case first.

107
MCQhard

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

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

zfill(5) pads the string '123' with ASCII zero characters on the left until the total length reaches the specified width. Because '123' has length 3 and the target width is 5, exactly 2 zeros must be prepended, yielding '00123'. This is the documented behavior and the only correct result.

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.

108
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

Because data was read as raw bytes from the IoT sensor, decode('utf-8') is the correct method to interpret those bytes as a Unicode string using the UTF-8 codec. This is the inverse of str.encode() and is exactly what bytes objects are designed to do. After decoding, the result is a normal str that can be compared, parsed, or logged as text.

Why this answer

The `recv()` method returns a bytes object. Since the data is valid UTF-8 and may contain non-ASCII characters, the correct way to convert bytes to a string is by calling `data.decode('utf-8')`. This method interprets the byte sequence according to the UTF-8 encoding and returns a Unicode string.

Exam trap

The trap here is confusing `encode()` and `decode()`: candidates often think bytes need to be 'encoded' to a string, but in Python, bytes are decoded to str, and str is encoded to bytes.

How to eliminate wrong answers

Option A is wrong because `data.encode('utf-8')` attempts to encode a bytes object, which raises an `AttributeError` (bytes have no `encode` method); encoding is for strings, not bytes. Option C is wrong because `bytes(data)` creates a copy of the bytes object, not a string, so it does not perform any conversion. Option D is wrong because `str(data)` returns a string representation like `b'...'` (including the `b` prefix and escapes), not the actual decoded text.

109
MCQmedium

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

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

With s = 'Python Programming', index 7 points to the uppercase 'P' that begins the second word, 'Programming'. A slice of s[7:] has no explicit stop index, so Python extends it to the string's full length, outputting every character from that 'P' through the final 'g'. The result is exactly 'Programming', the complete suffix of the original string.

Why this answer

The code likely uses slicing with a start index to extract 'Programming' from the string 'Python Programming'. For instance, 'Python Programming'[7:] returns the substring starting at index 7 (after 'Python ' which is 7 characters including space) to the end, which is 'Programming'. This operation is a common way to obtain a substring.

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.

110
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

The statement attempts to access an element using an index that is equal to or greater than the list's length, or a negative index less than -len(list). Python raises IndexError for any out-of-range sequence access, and the active except IndexError block catches this exact exception, printing the string 'Index out of range'. Since the handler successfully intercepts the exception, the program continues normally after the except block, making this the emitted output.

Why this answer

The code attempts to access an index that is outside the valid range of the string. In Python, strings are zero-indexed, so for a string of length n, valid indices are 0 to n-1. Accessing an index equal to or greater than the length raises an IndexError, which is exactly what 'Index out of range' describes.

Exam trap

The PCAP exam often tests the distinction between IndexError and ValueError, trapping candidates who confuse out-of-range indexing with invalid value operations, such as int('abc') which raises ValueError.

How to eliminate wrong answers

Option B is wrong because the code does produce output — specifically, an error message is printed to stderr when the IndexError occurs, so the program does not run silently without output. Option C is wrong because the program does not crash with an unhandled IndexError; Python's default behavior for an unhandled IndexError is to print a traceback and exit, which is not a 'crash' in the sense of a system-level failure, but rather a controlled termination with an error message. Option D is wrong because a ValueError is raised for invalid literal conversions or inappropriate argument types, not for index access beyond the string's length; the specific exception for out-of-range indexing is IndexError.

111
MCQhard

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

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

The string `C:\Users\John\Documents` (written as a raw string) contains 23 characters: `C`, `:`, `\`, `U`, `s`, `e`, `r`, `s`, `\`, `J`, `o`, `h`, `n`, `\`, `D`, `o`, `c`, `u`, `m`, `e`, `n`, `t`, `s`. Because it is a raw string, each backslash is its own character and none of the letters are escaped, so `len()` on this literal returns exactly 23.

Why this answer

The string "C:\\Users\\John\\Documents" uses double backslashes to represent literal backslashes. Each double backslash `\\` is a single backslash character. Counting all characters: C, :, \, U, s, e, r, s, \, J, o, h, n, \, D, o, c, u, m, e, n, t, s = 23 characters.

Thus, the length is 23.

Exam trap

The PCAP exam often tests the misconception that escape sequences like `\n` or `\t` are counted as single characters, when in fact each backslash is a separate character unless the string uses raw notation.

How to eliminate wrong answers

Option A is wrong because 21 would result from miscounting escape sequences as single characters (e.g., treating `\n` as one newline character). Option C is wrong because 22 might come from forgetting to count one of the backslashes or misinterpreting the number of escape sequences. Option D is wrong because 24 would occur if you counted an extra character, perhaps by including an additional quote or misreading the string length.

112
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

input_str.istitle() returns True exactly when the string is titlecased: each word boundary is followed by an uppercase letter, and all remaining letters in that word are lowercase. For a value like 'Hello World', both words start with an uppercase letter and the rest are lowercase, so the method returns True. This is the precise built-in predicate for checking titlecase, ignoring spaces and punctuation when identifying words.

Why this answer

`istitle()` returns `True` when the string is titlecased, meaning the first character of each word is uppercase and all other characters are lowercase. 'Hello World' has both words starting with an uppercase letter followed by lowercase letters, so it satisfies this condition.

Exam trap

Python often tests the distinction between `istitle()` and `isupper()` or `isalpha()`, trapping candidates who assume 'Hello World' is alphabetic or alphanumeric because they overlook the space character.

113
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

With s = 'abcdefgh', the slice s[7:3:-2] starts at index 7 (character 'h'), then subtracts 2 to reach index 5 (character 'f'), and stops before index 3 (character 'd') because the stop is exclusive. The step of -2 reverses the traversal direction and skips every other character. Hence the result is exactly 'hf'—first 'h', then 'f'.

Why this answer

The slice s[7:3:-2] starts at index 7 (character 'h'), goes backwards with step -2, and stops before index 3. The indices visited are 7 and 5, yielding 'h' and 'f', so the result is 'hf'. Option B is correct because the step is negative, meaning the slice moves from right to left, and the stop index is exclusive.

Exam trap

A common misconception is that a negative step reverses the start and stop indices, leading candidates to incorrectly assume the slice starts at the lower index and moves forward, or that the stop index is inclusive when the step is negative.

How to eliminate wrong answers

Option A is wrong because 'fh' would be the result if the slice started at index 5 and went forward with step 2 (e.g., s[5:7:2]), but here the step is -2 and the start is 7, so the order is reversed. Option C is wrong because 'h' would be the result if the slice were s[7:3:-1] and stopped after one step, but with step -2, two characters are included (indices 7 and 5). Option D is wrong because 'hfd' would require three characters from indices 7, 5, and 3, but index 3 is the exclusive stop and is not included, so only two characters are extracted.

114
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

This is the correct conversion: bytes.decode('utf-8') interprets the two-byte sequence 0xC3 0xA9 as the UTF-8 encoding of the Unicode code point U+00E9, which is the character 'é'. The decode() method is specifically designed to turn bytes back into a str using a specified codec, making this the exact inverse of 'é'.encode('utf-8'). The result is the Python string 'é'.

Why this answer

The byte string b'\xc3\xa9' is a UTF-8 encoded representation of the character 'é'. To convert it to a Python string, you must decode it using the .decode('utf-8') method, which interprets the bytes according to the UTF-8 encoding and returns a Unicode string.

Exam trap

The PCAP exam often tests the distinction between .encode() and .decode() on bytes vs. strings, trapping candidates who mistakenly use .encode() on bytes or try to decode with an incompatible codec like ASCII.

How to eliminate wrong answers

Option A is wrong because .encode('utf-8') is used to convert a string to bytes, not the reverse; calling it on a bytes object would raise an AttributeError. Option B is wrong because bytes objects do not have a .tostring() method; this is not a valid Python operation. Option C is wrong because str(b'\xc3\xa9', 'ascii') attempts to decode the bytes using ASCII, but the byte values 0xc3 and 0xa9 are outside the ASCII range (0-127), causing a UnicodeDecodeError.

115
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

splitlines() splits a string at Unicode line boundaries such as \n, \r\n, \r, \v, \f, and other line separator characters, returning a list of lines without the line terminators unless keepends=True is passed. It does not accept a separator argument and does not split on spaces or tabs, making it ideal for line-oriented data like file contents or multi-line text.

Why this answer

The `splitlines()` method splits a string at line boundaries (like \n, \r\n, or \r) and returns a list of substrings, making it a valid method for splitting a string into a list. It is specifically designed for handling multi-line strings.

Exam trap

The PCAP exam often tests the distinction between methods that return a list (`split`, `rsplit`, `splitlines`) versus those that return a tuple (`partition`, `rpartition`) or a single string (`join`), leading candidates to mistakenly select `partition` or `join`.

116
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

Using the format specifier {:,} or the equivalent f-string f"{1234567:,}" applies the comma format, which groups digits by thousands from right to left. The integer 1,234,567 is correctly grouped into the three-digit blocks 1, 234, and 567. Python's format mini-language explicitly adds thousands separators when the comma flag is present, so this is the definitive result of formatting the number as described.

Why this answer

The correct output is '1,234,567' because the format specifier '{:,}' uses the comma as a thousands separator in Python's string formatting. When applied to the integer 1234567, it inserts commas every three digits from the right, producing the locale-independent grouping.

Exam trap

The PCAP exam often tests whether candidates know that the comma in '{:,}' is a literal thousands separator, not a placeholder for any separator, and that it does not adapt to locale-specific symbols like periods or spaces.

How to eliminate wrong answers

Option A is wrong because it shows the number without any formatting, ignoring the comma separator specified in the format string. Option B is wrong because it uses periods as thousands separators, which is a European convention not produced by the comma specifier in Python's format() method. Option C is wrong because it uses spaces as thousands separators, which is not what the comma specifier does; spaces would require a different format specifier or locale settings.

117
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

capitalize() is a valid string method that creates and returns a new string with the first character converted to uppercase and all remaining characters converted to lowercase. Because strings are immutable, the original string is not modified, and the method call produces a copy. If the first character is not a letter (e.g., a digit or symbol), it remains unchanged while the rest of the string is lowercased.

Why this answer

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

118
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

`rsplit('.', 1)` splits from the right, limiting to one split, so only the final dot separates the extension; indexing `[-1]` returns the trailing segment `'pdf'`. This satisfies the stem's requirement to isolate the extension from `'document.pdf'`, and unlike `split`, it handles filenames containing multiple dots correctly.

Why this answer

`rsplit('.', 1)[-1]` splits the string from the right at the last occurrence of the dot, limiting to one split, and then retrieves the last element (index -1), which is the file extension. This handles filenames with multiple dots (e.g., 'archive.tar.gz') correctly, returning only the final extension.

Exam trap

The PCAP exam often tests the misconception that `split('.')[1]` is safe for extracting extensions, but the trap is that it fails for filenames with multiple dots or no dot, whereas `rsplit` with maxsplit handles these edge cases correctly.

How to eliminate wrong answers

Option A is wrong because `split('.')[1]` will fail with an IndexError if the filename has no dot, and for filenames with multiple dots it returns the second part (e.g., 'tar' from 'archive.tar.gz'), not the final extension. Option B is wrong because `split('.')[0]` returns the part before the first dot (e.g., 'document'), never the extension. Option D is wrong because `filename[-3:]` assumes the extension is exactly three characters, which fails for extensions like '.html' (returns 'tml') or '.py' (returns '.py' but only works by coincidence for three-letter extensions).

119
MCQeasy

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

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

The expression slices the string literal '12345' with a stop index that exceeds the string's length. Python's slice operation clamps out-of-range boundaries to the sequence's actual length, so it returns every character from index 0 through index 4. Thus the result is exactly the original five-character string '12345', with no error and no added whitespace.

Why this answer

In Python, slicing a string with a start index of 0 and an end index of 10 (as in '12345'[:10]) returns the entire string if the slice end exceeds the string length. Since '12345' has only 5 characters, the slice extracts all characters without padding or error, resulting in '12345'.

Exam trap

The PCAP exam often tests the misconception that slicing beyond the string length causes an IndexError or that Python automatically pads the result to the specified length, leading candidates to choose A or C instead of recognizing the graceful truncation.

How to eliminate wrong answers

Option A is wrong because it incorrectly assumes Python pads the slice with spaces to reach length 10, but slicing never adds padding—it only extracts existing characters. Option C is wrong because Python slicing does not raise an IndexError when the end index is beyond the string length; it simply returns the substring up to the actual length. Option D is wrong because it includes a trailing space, but slicing does not append any characters, even a single space.

120
MCQhard

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

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

This is exactly the output of the slice `'Python'[::-1]`, which steps through the string from the last character to the first with a step of -1. Python's slicing mechanism creates a new string by copying the characters in reverse order while preserving each character's case and position relative to the others. Because the original string begins with an uppercase 'P', that 'P' appears at the final index, yielding 'nohtyP'.

Why this answer

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.

121
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

Python's `in` operator for strings performs a substring containment test, checking whether the left operand appears as a contiguous sequence within the right operand. In 'abc', the two-character sequence 'ab' is present at indices 0 and 1, so the expression evaluates to True. This is exact, character-by-character matching with no wildcard or fuzzy semantics.

Why this answer

The `in` operator checks if the substring 'ab' appears anywhere within the string 'abc'. Since 'abc' contains the consecutive characters 'a' followed by 'b', the expression evaluates to True.

Exam trap

The trap here is that candidates may confuse the `in` operator with checking individual characters in any order, or mistakenly think that a longer substring can be found in a shorter string, leading them to select option E.

122
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

str.isdigit() returns True only when the string is non-empty and every character has the Unicode Numeric_Type of Digit or Decimal, which includes ASCII '0'-'9', non-Arabic decimal digits, and compatibility superscripts such as '²'. This is the broadest check that still excludes letters, punctuation, and numeric fractions, so it is the correct method when the requirement is to verify that a string contains only digits.

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.

123
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

This is the exact string returned by the join() operation: a single string containing the characters 'a', a space, 'b', another space, and 'c'. In an interactive Python session or when using repr(), the result is shown with single quotes around it to clearly delimit it as a textual string object. The single quotes are part of the representation, not the actual data, and they confirm the value is a str, not a list or other container.

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.

124
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

This is the correct output: r'\s+' matches one or more whitespace characters as a single delimiter, so the spaces before and after words are consumed. With the input 'one two three', each word is separated by exactly one space, and there is no leading/trailing whitespace, yielding exactly three substrings. The regex engine advances past all matching whitespace, so no empty strings appear.

Why this answer

`re.split(r'\s+', 'one two three')` splits the string on one or more whitespace characters (`\s+`). The pattern consumes all contiguous whitespace as a single delimiter, producing a list of the three non-empty substrings: `['one', 'two', 'three']`. No trailing empty string is included because the string does not end with whitespace.

Exam trap

The PCAP exam often tests the distinction between splitting on a single character vs. a regex quantifier like `+`, leading candidates to mistakenly think each space produces a separate list element or that trailing delimiters always produce empty strings.

How to eliminate wrong answers

Option A is wrong because it incorrectly suggests the output is a single-element list containing the original string, which would only happen if the pattern never matched (e.g., using a non-existent delimiter). Option B is wrong because it includes a trailing empty string, which would occur only if the string ended with a delimiter (e.g., `'one two three '`), but the input has no trailing whitespace. Option D is wrong because it treats each individual space character as a separate delimiter, which would happen with a pattern like `r' '` (single space) rather than `r'\s+'` (one or more whitespace).

125
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

The positive lookahead (?=AA) matches the zero-width position where the substring 'AA' begins, without consuming any characters, so the regex engine can find overlapping occurrences at every starting index. re.findall returns one empty-string match for each such position, so len() gives the exact count of overlapping occurrences. This is efficient because the regex engine scans the string once in O(n) time for a literal pattern, with no substring copying or manual index stepping. It is the cleanest solution when overlapping matches must be counted.

Why this answer

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

126
MCQhard

Consider the following code: print('"age": 30,')

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

This is the exact third line of the pretty-printed JSON output when `indent=2` is used. The line begins with two spaces (the indentation for properties at the top level), then the key `"age"`, a colon and a space, and the value `30`, followed by a trailing comma. That comma is required because the `"city"` property still follows; this line matches the code's actual output verbatim.

Why this answer

The code prints a literal string: "age": 30,. The double quotes are escaped within the single-quoted string, so they appear in the output. The trailing comma is part of the string, not a delimiter.

Exam trap

This question tests attention to detail: the string includes a trailing comma, which is easy to overlook if the candidate assumes it's a dictionary serialization.

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.

127
Multi-Selecteasy

Which TWO of the following string methods return a new string without modifying the original?

Select 2 answers
A.index()
B.replace()
C.strip()
D.find()
E.count()
AnswersB, C

The replace() method takes two substrings and returns a brand-new string in which all non-overlapping occurrences of the first substring have been replaced with the second. Since strings are immutable, the original string is untouched; instead, the method constructs a new string and returns it. This precisely matches the condition of returning a new string.

Why this answer

The `replace()` method returns a new string with all occurrences of a substring replaced by another substring, without altering the original string. Similarly, `strip()` returns a new string with leading and trailing whitespace (or specified characters) removed, leaving the original unchanged. Both methods are non-mutating because strings in Python are immutable.

Exam trap

Python Institute often tests the distinction between methods that return a new string (like `replace()` and `strip()`) versus those that return an index or count (like `index()`, `find()`, and `count()`), trapping candidates who confuse 'returning a value' with 'returning a new string'.

128
MCQmedium

What is the output of the following code? s = 'Hello'; print(s.find('l'))

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

Option 2 is correct: the string 'hello' has the character positions h(0), e(1), l(2), l(3), and o(4). When str.index('l') is called, Python scans the string left-to-right and returns the smallest index where the substring 'l' occurs, which is 2. Therefore the code prints the integer 2.

Why this answer

The `str.find()` method returns the lowest index of the first occurrence of the substring. In the string 'Hello', the character 'l' first appears at index 2 (0-based indexing: H=0, e=1, l=2). Therefore, `s.find('l')` returns 2, making option B correct.

Exam trap

PCAP often tests the distinction between 0-based and 1-based indexing, and the fact that `find()` returns the first occurrence, not the last or any subsequent one.

How to eliminate wrong answers

Option A is wrong because it assumes 1-based indexing, but Python uses 0-based indexing, so the first 'l' is at index 2, not 1. Option C is wrong because index 0 corresponds to 'H', not 'l'. Option D is wrong because index 3 corresponds to the second 'l' in 'Hello', but `find()` returns the first occurrence, which is at index 2.

129
Multi-Selecthard

Which THREE of the following expressions return the string "Python"? (Choose three.)

Select 3 answers
A."Python"[::2]
B."Python"[:]
C."Python"[0:6:1]
D."Python"[0:6]
E."Python"[:-1]
AnswersB, C, D

The expression `"Python"[:]` is a full slice: both the start and stop indices are omitted, and the step defaults to 1. With these defaults, Python interprets the slice as starting at index 0 and stopping at the length of the sequence, thereby including every character in order. This idiom is commonly used to create a copy of a sequence; here it returns a new string object containing exactly the same characters as the original: `'Python'`.

Why this answer

Slicing the entire string with '[:]' returns a copy of the full string, which is 'Python'. This is a common idiom for copying a sequence in Python.

Exam trap

A common trap is the misconception that a slice with a step other than 1 (e.g., '::2') returns the full string, or that negative step or omitted stop index produces the same result as a full slice.

130
Multi-Selecteasy

Which TWO of the following are immutable in Python?

Select 2 answers
A.Set
B.Tuple
C.String
D.Dictionary
E.List
AnswersB, C

Tuples are immutable sequences; once created, their contents cannot be changed, added, or removed. Although tuples can contain mutable objects (like a list), the tuple's own structure and element references are fixed, making it hashable only if all elements are hashable. This immutability allows tuples to serve as dictionary keys when they contain only immutable elements.

Why this answer

Tuple (B) is immutable because once created, its elements cannot be added, removed, or changed. This is enforced by Python's internal structure: tuples are stored as a fixed-length array of PyObject pointers, and any attempt to modify them raises a TypeError.

Exam trap

Python Institute often tests the misconception that strings are mutable because they support indexing and slicing, but candidates forget that any operation that appears to change a string actually returns a new string object, leaving the original unchanged.

131
Multi-Selectmedium

Which TWO of the following string methods modify the string in place? (Note: Python strings are immutable.)

Select 2 answers
A.str.join()
B.str.lower()
C.str.upper()
D.str.replace()
E.str.strip()
AnswersB, C

str.lower() returns a new string with all characters lowercased; the original string remains unchanged.

Why this answer

None of the listed string methods modify the string in place because Python strings are immutable. All string methods return a new string rather than altering the original. Therefore, there are no correct options for this question.

Exam trap

The question is designed to test the understanding that strings are immutable. The trap is that candidates may incorrectly believe that methods like replace() or strip() modify the string in place, but in fact no string method modifies the original string.

132
Multi-Selecthard

Which THREE are valid escape sequences in Python strings?

Select 3 answers
A.\n
B.\q
C.\\
D.\t
E.\z
AnswersA, C, D

In Python string literals, the backslash introduces an escape sequence, and \n specifically represents the line feed character (ASCII 10), which advances the cursor to the next line. This is one of the most commonly used escapes for creating multiline output or separating lines in text. Although written as two characters in source code, \n is stored as a single character in the resulting string, making it a single indexable element.

Why this answer

\n is a standard escape sequence in Python that represents a newline character (ASCII LF, 0x0A). It is defined in the Python language specification and is commonly used to insert line breaks in string literals.

Exam trap

Python Institute often tests the distinction between valid escape sequences (like \n, \\, \t) and invalid ones (like \q, \z) that beginners might assume exist because they see other backslash combinations in contexts like regex or shell scripting.

133
Multi-Selectmedium

Which THREE of the following are valid string methods in Python? (Choose three.)

Select 3 answers
A..capitalize()
B..lower()
C..uppercase()
D..titlecase()
E..swapcase()
AnswersA, B, E

.capitalize() is a built-in string method that capitalizes the first character and lowercases the rest.

Why this answer

All three options A, B, and E are valid Python string methods. .capitalize() returns a copy of the string with its first character capitalized and the rest lowercased. .lower() returns a copy of the string with all characters converted to lowercase. .swapcase() returns a copy of the string with uppercase characters converted to lowercase and vice versa. Options C and D are incorrect because .uppercase() and .titlecase() are not valid Python string methods; the correct methods are .upper() and .title(). Although the question asks to choose two, note that .swapcase() is also a valid method, making three correct options.

In such cases, any two of the three valid methods would be acceptable, but the intended correct answers are A, B, and E.

Exam trap

Python Institute tests exact method names. The trap is that .swapcase() is a valid method, so candidates may incorrectly exclude it if they think only two are valid. Additionally, .uppercase() and .titlecase() are common confusions with the real methods .upper() and .title().

134
MCQeasy

What is the result of the expression 'Hello'[1:3]?

A.'el'
B.'lo'
C.'He'
D.'ell'
AnswerA

Python slicing uses a half-open interval: the start index is included, but the stop index is excluded. In 'hello', the indices are h=0, e=1, l=2, l=3, o=4, so slice [1:3] selects index 1 ('e') and index 2 ('l'), producing 'el'. The character at index 3 is not part of the result because the stop boundary is exclusive.

Why this answer

In Python, string slicing uses the syntax `string[start:stop]`, where `start` is inclusive and `stop` is exclusive. For `'Hello'[1:3]`, the indices are: index 1 = 'e', index 2 = 'l', and index 3 is not included, so the slice returns 'el'. This is a fundamental string slicing behavior defined in Python's sequence protocol.

Exam trap

Python Institute often tests the off-by-one error in slice stop indices, where candidates mistakenly think the stop index is inclusive and select 'ell' (option D) instead of the correct 'el'.

How to eliminate wrong answers

Option B is wrong because 'lo' would result from slicing `[3:5]` (indices 3 and 4), not `[1:3]`. Option C is wrong because 'He' would result from slicing `[0:2]` (indices 0 and 1), not `[1:3]`. Option D is wrong because 'ell' would result from slicing `[1:4]` (indices 1, 2, and 3), but the stop index 3 excludes index 3, so only two characters are taken.

135
MCQhard

Which of the following expressions raises a ValueError?

A.'abc'.index('a')
B.'abc'.find('d')
C.'abc'.rfind('d')
D.'abc'.index('d')
AnswerD

Here, str.index() is invoked with 'd', which does not occur in the string 'abc'. Unlike find/rfind, index is designed to raise ValueError when the substring is absent, treating that condition as an exceptional event. Because 'd' is missing, this expression raises ValueError, making it the correct answer.

Why this answer

Calling `'abc'.index('d')` raises a `ValueError` when the substring is not found. The `str.index()` method in Python is designed to raise this exception for missing substrings, unlike `str.find()` and `str.rfind()`, which return -1.

Exam trap

Python Institute often tests the subtle difference between `index()` (which raises an exception) and `find()`/`rfind()` (which return -1), trapping candidates who assume all substring search methods behave identically on failure.

How to eliminate wrong answers

Option A is wrong because `'abc'.index('a')` successfully finds the substring 'a' at index 0, so no exception is raised. Option B is wrong because `'abc'.find('d')` returns -1 when the substring is not found, as per Python's string method behavior. Option C is wrong because `'abc'.rfind('d')` also returns -1 for a missing substring, following the same convention as `find()`.

136
Multi-Selecteasy

Which two of the following are valid ways to create a multiline string in Python source code? (Choose two.)

Select 2 answers
A.s = "Line1\nLine2"
B.s = 'Line1' 'Line2'
C.s = """Line1\nLine2"""
D.s = '''Line1\nLine2'''
E.s = 'Line1\nLine2'
AnswersC, D

Triple double quotes define a multiline string literal: the opening and closing delimiters may be on different physical lines, and any raw line breaks inside become part of the string. Including \n adds an explicit line break as well; this is one of the two accepted forms for multiline literals in Python.

Why this answer

Triple-quoted strings ("""...""") in Python allow multiline content directly in source code, including explicit escape sequences like \n. The triple quotes preserve the string as a single object spanning multiple lines, making it a valid multiline string.

Exam trap

The PCAP exam often tests the distinction between a string that contains a newline character (via \n) and a string that is physically multiline in source code, tricking candidates into thinking any string with \n is a multiline string.

137
Matchingmedium

Match each variable scope to its description.

Drag a concept onto its matching description — or click a concept then click the description.

Concepts
Matches

Inside a function

At module level

In outer function (nested)

Predefined names in Python

Variable from enclosing scope (not global)

Why these pairings

The LEGB rule defines scope lookup order: Local, Enclosing, Global, Built-in. Correct matches are Local (inside function), Enclosing (outer function), Global (module level). Built-in consists of Python's predefined names.

138
MCQmedium

A developer is building a configuration parser. They have a string `line = " key = value "` and need to remove the leading and trailing spaces, then split the line at the equals sign into a list of exactly two elements: the key and the value, with any spaces around the equals sign removed. Which expression achieves this?

A.[part.strip() for part in line.split('=')]
B.line.strip().split('=')
C.line.replace(' ', '').split('=')
D.line.strip(' =').split('=')
AnswerA

Splitting the original string on '=' gives [' key ', ' value ']. The list comprehension then applies .strip() to each part, removing all leading and trailing whitespace from both the key and the value. This yields ['key', 'value'], exactly two elements with spaces around the equals sign removed, satisfying the requirement.

Why this answer

The goal is to remove whitespace around both the key and the value after splitting. Splitting first on the equals sign isolates the two components, and then stripping each component individually removes spaces that surround the equals sign. The list comprehension does this cleanly and preserves any internal spaces that belong to the key or value, making it the correct approach.

Exam trap

The trap here is assuming that stripping the whole line before splitting is enough to remove spaces around the delimiter, when in fact those spaces remain attached to the resulting substrings.

139
Multi-Selecteasy

Which TWO of the following operations can be performed on a string?

Select 2 answers
A.Extend with .extend()
B.Append with .append()
C.Pop with .pop()
D.Slicing with [::]
E.Concatenation with +
AnswersD, E

Slicing with [::] is a valid, non-mutating operation on strings because str implements the sequence protocol via __getitem__, accepting a slice object. For example, s[::-1] creates a reversed copy of the string, while s[1:4] extracts a substring; in every case the result is always a brand-new string and the original is left unchanged. This works regardless of the immutability of strings because it reads data rather than trying to modify it.

Why this answer

String slicing with the syntax `[start:stop:step]` (e.g., `[::]`) is a built-in operation for strings in Python, allowing extraction of substrings. Option E is correct because the `+` operator performs string concatenation, creating a new string by joining two strings together.

Exam trap

Python Institute often tests the distinction between mutable (list) and immutable (string) types, leading candidates to incorrectly assume that list methods like `.append()`, `.extend()`, and `.pop()` also work on strings.

140
MCQeasy

A developer wants to check if a string ends with a specific suffix. Which method should be used?

A.endswith()
B.index()
C.find()
D.startswith()
AnswerA

The `endswith()` method is the dedicated predicate for suffix testing: it returns `True` only when the final characters of the string exactly match the given suffix, and `False` otherwise. It also accepts optional `start`/`end` slice arguments, which allow you to check only a portion of the string, and it performs a case-sensitive comparison by default (use `casefold()` or lowercasing for case-insensitive checks). Because it returns a boolean directly, it cleanly satisfies the developer's requirement to verify whether the string ends with a specific substring.

Why this answer

The `endswith()` method is specifically designed to check if a string ends with a given suffix, returning a boolean value. This is the correct and most direct approach for the task described, as it avoids manual slicing or comparison.

Exam trap

Python Institute often tests the distinction between `endswith()` and `startswith()`, trapping candidates who confuse prefix and suffix checks, or who mistakenly use `find()` or `index()` which locate substrings anywhere in the string rather than at the end.

How to eliminate wrong answers

Option B is wrong because `index()` returns the lowest index where a substring is found, or raises a ValueError if not found, and does not check for a suffix. Option C is wrong because `find()` returns the lowest index of the substring or -1 if not found, but does not test for the end of the string. Option D is wrong because `startswith()` checks if the string begins with a prefix, not a suffix.

141
MCQhard

A developer needs to format a floating-point number 123.456789 with exactly 2 decimal places and a width of 10 characters, right-aligned. Which format specifier accomplishes this?

A.:.2f
B.:10.2g
C.:10.2e
D.:10.2f
AnswerD

The specifier `:10.2f` is the correct choice: `10` sets a minimum field width of 10 characters, `.2` requires exactly two digits after the decimal point, and `f` selects fixed-point notation with no exponent. When applied to `1234567`, it produces `1234567.00`, which is exactly 10 characters (7 integer digits, the decimal point, and 2 fractional digits) and satisfies the width and precision requirements. If the integer part were shorter, leading spaces would pad the output to the specified width.

Why this answer

The format specifier `:10.2f` combines a total width of 10 characters with exactly 2 decimal places for a floating-point number, right-aligned by default. The `f` type ensures fixed-point notation, and the width of 10 includes the decimal point and digits, padding with spaces on the left.

Exam trap

The PCAP exam often tests the distinction between `f`, `g`, and `e` format types, and the trap here is that candidates confuse the precision meaning (decimal places vs. significant digits) or forget that width must be explicitly specified for padding.

How to eliminate wrong answers

Option A is wrong because `:.2f` specifies only 2 decimal places without a width, so the output is not padded to 10 characters. Option B is wrong because `:10.2g` uses general format, which may switch to scientific notation for large or small numbers and does not guarantee exactly 2 decimal places. Option C is wrong because `:10.2e` forces scientific (exponential) notation with 2 digits after the decimal, producing output like '1.23e+02' instead of the required fixed-point format.

142
MCQhard

A developer writes a function to reverse a string: def reverse_str(s): return s[::-1]. Which of the following statements about this function is true?

A.It only works for strings with even length
B.It returns a new reversed string
C.It modifies the original string
D.It raises an error if s is empty
AnswerB

In Python, strings are immutable sequences, so slicing with s[::-1] does not alter the original object; it constructs a completely new string with the characters in reverse order. The original variable s still references the unchanged string, and the newly created string can be assigned to another name or used directly. This is the canonical way to reverse a string, and it correctly returns a new value rather than mutating existing data.

Why this answer

The slice operation `s[::-1]` creates a new string that is the reverse of the original. Strings in Python are immutable, so any operation that appears to modify a string actually returns a new string object. The original string `s` remains unchanged.

Exam trap

The PCAP exam often tests the immutability of strings and the behavior of slicing, trapping candidates who mistakenly think that string operations modify the original object or that slicing fails on empty sequences.

How to eliminate wrong answers

Option A is wrong because `s[::-1]` works correctly for strings of any length, including odd-length and empty strings. Option C is wrong because strings in Python are immutable; the slice operation does not modify the original string but returns a new one. Option D is wrong because an empty string `''` is a valid string; slicing it with `[::-1]` returns an empty string without raising an error.

143
MCQmedium

A developer tries to modify a string: s = 'hello'; s[0] = 'H'. What happens when this code runs?

A.It changes the string to 'Hello'
B.It raises a TypeError: 'str' object does not support item assignment
C.It creates a new string 'Hello' and assigns it to s
D.It raises an IndexError because index 0 is out of range
AnswerB

Strings in Python are immutable sequences; the assignment `s[0] = 'H'' attempts to mutate the object at index 0, which violates the immutable contract of the `str` type. The interpreter raises a `TypeError` specifically because `str` objects lack a `__setitem__` method, preventing item assignment. This directly satisfies the constraint that strings cannot be modified in-place in Python.

Why this answer

Strings in Python are immutable, meaning their contents cannot be changed after creation. Attempting to assign a new character to an index position (e.g., s[0] = 'H') raises a TypeError: 'str' object does not support item assignment. To modify a string, you must create a new string using slicing or concatenation.

Exam trap

The PCAP exam often tests the immutability of strings by presenting an assignment to an index, tricking candidates who confuse strings with mutable sequences like lists into thinking the string will be modified in place.

How to eliminate wrong answers

Option A is wrong because strings are immutable; assigning to an index does not modify the string in place, so it does not change to 'Hello'. Option C is wrong because Python does not automatically create a new string and reassign s; instead, it raises an error immediately. Option D is wrong because index 0 is valid for a non-empty string like 'hello'; the error is a TypeError, not an IndexError.

144
MCQeasy

A developer needs to extract the file extension from a string like 'report.pdf'. Which string method is most appropriate?

A.str.find('.')
B.str.split('.')[-1]
C.str.partition('.')[2]
D.str.rstrip('.pdf')
AnswerB

str.split('.')[-1] is the correct idiom because it divides the entire string on every dot and then uses -1 to select the final element, which is exactly the substring after the last period. This handles file names with multiple dots, returning the last component as the extension. One caveat is that if no dot exists, the whole original string is returned, but for typical extension extraction this is acceptable and widely used.

Why this answer

`str.split('.')[-1]` splits the string at each dot and returns the last element, which is the file extension. This method works reliably for simple cases like 'report.pdf' and is a common Python idiom for extracting extensions.

Exam trap

Python Institute often tests the distinction between `partition()` and `split()` — candidates mistakenly choose `partition()` because it seems simpler, but they overlook that `partition()` only splits on the first occurrence, making it unsuitable for extensions in filenames with multiple dots.

How to eliminate wrong answers

Option A is wrong because `str.find('.')` returns the index of the first dot, not the extension itself. Option C is wrong because `str.partition('.')[2]` returns everything after the first dot, which works for 'report.pdf' but fails for strings with multiple dots (e.g., 'archive.tar.gz' returns 'tar.gz' instead of 'gz'). Option D is wrong because `str.rstrip('.pdf')` removes trailing characters that match any character in '.pdf' (not the exact substring), so it would incorrectly strip 'f' from 'report.pd' or remove more than intended.

145
Multi-Selectmedium

Which THREE of the following are valid escape sequences in Python strings?

Select 3 answers
A.\g
B.\t
C.\h
D.\r
E.\n
AnswersB, D, E

The sequence \t is a valid escape sequence that represents the tab character (ASCII 9, horizontal tab). It is commonly used to insert whitespace alignment in text output, for example in printing columns or formatting tables. Python recognizes \t as a single character with the ordinal value 9, not as two separate characters backslash and 't'.

Why this answer

\t is the standard escape sequence for a horizontal tab character in Python strings. Escape sequences in Python begin with a backslash followed by a specific character, and \t is defined in the Python language specification (similar to C) to represent the ASCII tab character (0x09).

Exam trap

Python Institute often tests the distinction between valid escape sequences and invalid ones that are silently treated as literal characters, leading candidates to mistakenly think any backslash-letter combination is valid.

146
Multi-Selecthard

In a performance-critical application, you need to concatenate many strings in a loop. Which TWO approaches are most efficient?

Select 2 answers
A.Using the % formatting operator
B.Using the join() method on a list
C.Using the += operator
D.Using the + operator
E.Using StringIO from the io module
AnswersB, E

Using the join() method on a list: This is the canonical efficient technique. You collect all the pieces into a list, then call separator.join(list) once. The join() implementation precomputes the exact total length of the result, allocates a single buffer, and copies each piece into it in one straight pass, producing no intermediate strings. That makes it O(n) in both time and memory and is the fastest pure-Python way to assemble many separate string fragments.

Why this answer

The `join()` method on a list (Option B) is efficient because it allocates memory once for the final concatenated string, avoiding repeated reallocation and copying that occurs with immutable strings. `StringIO` (Option E) provides a mutable buffer that accumulates string fragments efficiently, making it suitable for high-performance concatenation in loops.

Exam trap

The PCAP exam often tests the misconception that `+=` is efficient for string concatenation in loops, when in fact it is O(n²) due to string immutability, while `join()` and `StringIO` are the correct O(n) approaches.

147
MCQhard

Under CPython, what is the result of the following code? a = 'hello'; b = 'hello'; print(a is b)

A.True
B.False
C.NameError
D.None
AnswerA

True is correct because in CPython, string literals are automatically interned, meaning that two identical string literals are stored in the same memory location. When the code compares them with the identity operator 'is', it compares object memory addresses, and since both variables point to the same interned object, the result is True. This is a well-known CPython behavior, though it is an implementation detail rather than part of the Python language specification. The exact code likely creates two variables with the same string literal, and interning makes their identities match.

Why this answer

CPython interns short strings as an optimization, meaning both variables 'a' and 'b' reference the same immutable string object in memory. The 'is' operator checks object identity, not value equality, so it returns True when both variables point to the same interned object.

Exam trap

The Python Institute often tests the distinction between 'is' (identity) and '==' (equality), and the trap here is that candidates assume 'is' compares values, leading them to incorrectly choose False when they think two separate string objects are created.

How to eliminate wrong answers

Option B is wrong because it assumes that two identical string literals always create separate objects, but CPython's string interning for short strings (like 'hello') causes them to share the same memory address. Option C is wrong because both 'a' and 'b' are defined and assigned valid string values, so no NameError occurs. Option D is wrong because the 'is' operator always returns a boolean (True or False), never None, and in this case it returns True.

148
MCQmedium

Which of the following best describes the immutability of strings in Python?

A.Strings can be modified in place using indexing.
B.Strings are mutable but require special methods.
C.Strings cannot be reassigned.
D.Strings cannot be changed after creation, but variables can be reassigned.
AnswerD

This is the correct distinction: the str object itself is immutable, so once a string is created its contents cannot be altered, added to, or removed. However, a variable that references a string can be assigned a new value, such as s = 'new', which makes the variable point to a different string object. This separation between object identity and variable binding is fundamental to Python's data model and explains why strings can appear to 'change' when they actually are being replaced.

Why this answer

Strings in Python are immutable objects, meaning once a string is created, its contents cannot be changed. However, the variable referencing the string can be reassigned to point to a new string object. This distinction between mutability of the object and reassignment of the variable is fundamental to Python's data model.

Exam trap

Python Institute often tests the confusion between object mutability and variable reassignment, leading candidates to incorrectly believe that strings can be modified in place or that they cannot be reassigned at all.

How to eliminate wrong answers

Option A is wrong because strings do not support item assignment; attempting to modify a string via indexing (e.g., s[0] = 'a') raises a TypeError. Option B is wrong because strings are immutable, not mutable, and no special methods can change them in place; any operation that appears to modify a string actually creates a new string object. Option C is wrong because strings themselves can be reassigned to new variables or the same variable can be bound to a different string; the statement 'cannot be reassigned' confuses variable rebinding with object immutability.

149
Multi-Selectmedium

Which two methods can be used to remove leading whitespace from a string? (Choose two.)

Select 2 answers
A.s.strip()
B.s.lstrip()
C.s.split()
D.s.chomp()
E.s.rstrip()
AnswersA, B

Calling s.strip() returns a new string with all leading and trailing whitespace removed, so leading whitespace is indeed eliminated as part of the process. This makes it a valid choice for the task, even though it also strips the right end. By default, strip() removes spaces, tabs, and newline characters; an optional chars argument can narrow the set.

Why this answer

`s.strip()` removes both leading and trailing whitespace from the string, including spaces, tabs, and newline characters. This method is commonly used when you need to clean up a string entirely, but it does more than just leading whitespace removal.

Exam trap

The trap here is that candidates may incorrectly consider `s.strip()` as the method for removing only leading whitespace, overlooking that `lstrip()` is the precise method. Additionally, `chomp()` is not a Python string method; it is from Ruby, and `split()` and `rstrip()` do not remove leading whitespace.

150
MCQeasy

A programmer writes a function that expects a string and returns it reversed. Which code snippet correctly reverses the string 'stressed' to 'desserts'?

A.result = s.reversed()
B.result = s[::-1]
C.s.reverse()
D.result = ''.join(reversed(s))
AnswerB, D

Using extended slice syntax with a step of `-1` creates a reversed copy of the entire string: `s[::-1]` means start at the end, go to the beginning, and step backward by one. This is the most idiomatic and concise way to reverse a string in Python, and it is often preferred for its readability and speed. Since strings are immutable, this operation allocates a new string object containing the characters in reverse order, leaving the original string unchanged.

Why this answer

Both option B and option D correctly reverse the string 'stressed' to 'desserts'. Option B uses slice notation `[::-1]`, which creates a reversed copy of the string by stepping from end to start with a step of -1. This is the most direct and idiomatic way to reverse a string in Python.

Option D uses `''.join(reversed(s))`: `reversed(s)` returns an iterator that yields characters in reverse order, and `join()` concatenates them into a new string. This is also a valid and correct approach. Option A is incorrect because strings do not have a `reversed()` method; `reversed()` is a built-in function.

Option C is incorrect because `.reverse()` is a list method, not a string method, and strings are immutable.

Exam trap

The Python Institute often tests whether candidates know that both slice notation `[::-1]` and the combination of `reversed()` with `join()` are valid ways to reverse a string. Candidates may incorrectly think only slicing is correct or overlook that `reversed()` returns an iterator that requires `join()` to produce a string.

How to eliminate wrong answers

Option A is wrong because `s.reversed()` is not a valid method; the correct built-in is `reversed(s)`, which returns a reverse iterator, not a string. Option C is wrong because `s.reverse()` is a list method, not a string method — strings are immutable and have no `.reverse()` method, so this raises an AttributeError. Option D is wrong because while `''.join(reversed(s))` does produce the reversed string, it is not listed as the correct answer in the given options; the question asks for the snippet that correctly reverses the string, and option B is the direct, idiomatic one-liner.

← PreviousPage 2 of 3 · 151 questions totalNext →

Ready to test yourself?

Try a timed practice session using only Strings questions.