Courseiva

CCNA Strings Questions

74 of 151 questions · Page 1/3 · Strings topic · Answers revealed

1
MCQmedium

A developer is writing a function to reverse each word in a sentence while preserving the original order of the words. For example, 'Hello World' should become 'olleH dlroW'. The current implementation is: def reverse_words(s): return ' '.join(word[::-1] for word in s.split()). This works for simple cases. However, the input may contain multiple spaces between words (e.g., 'Hello World') and tabs. The requirement is to preserve the exact whitespace between words (including tabs and multiple spaces) in the output. Which of the following modifications will achieve this while keeping the approach efficient?

A.Use s.split(' ') and handle empty strings to preserve spaces, but ignore tabs
B.Iterate over the string, detect word boundaries, and build a new string manually
C.Use re.split(r'(\s+)', s) to separate words and whitespace, then reverse the word parts and join back
D.Use s.split() and then join with the original spaces using a separate loop that tracks whitespace
AnswerC

Splitting on whitespace collapses runs of spaces and tabs, losing the original separators. Capturing the whitespace with re.split(r'(\s+)') keeps those groups in the list, so reversing only the word elements and rejoining preserves exact spacing.

Why this answer

`re.split(r'(\s+)', s)` splits the string into a list where every other element is a whitespace segment (preserving exact spaces and tabs), and the word segments can be reversed individually. Joining the list back with `''.join(...)` reconstructs the original whitespace exactly, meeting the requirement efficiently without manual iteration.

Exam trap

The Python Institute often tests the distinction between `str.split()` (which collapses all whitespace) and `re.split` with a capturing group (which preserves whitespace), and the trap here is assuming that simple `split` and `join` can handle arbitrary whitespace patterns without losing information.

How to eliminate wrong answers

Option A is wrong because `s.split(' ')` splits only on single spaces, not tabs, and handling empty strings does not preserve multiple spaces or tabs correctly. Option B is wrong because manually iterating and detecting word boundaries is inefficient and error-prone, and the PCAP exam expects use of built-in or regex solutions. Option D is wrong because `s.split()` collapses all whitespace (including tabs and multiple spaces) into single spaces, losing the original whitespace pattern, and a separate loop to track whitespace would be complex and not preserve tabs.

2
MCQmedium

Refer to the exhibit. What happens when the code is executed?

A.The string becomes "Hallo"
B.A TypeError is raised
C.A SyntaxError is raised
D.The code runs without error and s remains "Hello"
AnswerB

The code combines incompatible operand types, such as concatenating a string with an integer or calling an unsupported operation on a value, so the interpreter halts and raises a TypeError rather than producing output or a different exception class.

Why this answer

The code attempts to modify a string by assigning a new character to an index position (s[0] = 'H'). Strings in Python are immutable, meaning their elements cannot be changed after creation. This operation raises a TypeError because the item assignment is not supported for string objects.

Exam trap

Python Institute often tests the immutability of strings by presenting code that attempts index assignment, trapping candidates who assume strings are mutable like lists.

How to eliminate wrong answers

Option A is wrong because strings are immutable, so the assignment s[0] = 'H' does not change the string to 'Hallo'; instead, it raises an error. Option C is wrong because the syntax is valid Python syntax for item assignment; the error is a runtime TypeError, not a syntax error. Option D is wrong because the code does not run without error; it raises a TypeError due to the immutable nature of strings.

3
MCQhard

A QA engineer needs to verify that a user input string contains at least one uppercase letter, one lowercase letter, and one digit. Which regex pattern can be used with re.search() to achieve this?

A.r'(?=.*[A-Z])(?=.*[a-z])(?=.*\d)'
B.r'[A-Za-z0-9]'
C.r'([A-Z].*[a-z].*\d)|([a-z].*[A-Z].*\d)|...'
D.r'\d.*[a-z].*[A-Z]'
AnswerA

This pattern uses three zero-width positive lookahead assertions evaluated from the same starting position. Each (?=...) checks that, from that position, .* can reach at least one uppercase letter, one lowercase letter, and one digit. Since lookaheads consume no characters, all three requirements are verified simultaneously and in any order, making the match succeed exactly when all categories appear somewhere in the string.

Why this answer

It uses lookahead assertions ((?=...)) to check for the presence of at least one uppercase letter, one lowercase letter, and one digit anywhere in the string, without consuming characters. This allows re.search() to return a match if all three conditions are met, regardless of order.

Exam trap

The PCAP exam often tests the distinction between character classes and lookahead assertions, trapping candidates who think a simple character class like [A-Za-z0-9] can enforce the presence of each type, when it only matches a single character from the union.

How to eliminate wrong answers

Option B is wrong because it matches any single character that is a letter or digit, but does not ensure that all three required character types (uppercase, lowercase, digit) are present. Option C is wrong because it attempts to enumerate all possible orderings of the three character types, which is impractical and incomplete; it also contains a syntax error with the trailing ellipsis. Option D is wrong because it requires the digit to appear before the lowercase letter and the lowercase letter before the uppercase letter, enforcing a specific order that is not required by the problem.

4
Multi-Selectmedium

Which THREE of the following are immutable types in Python?

Select 3 answers
A.str
B.bytes
C.bytearray
D.list
E.tuple
AnswersA, B, E

Strings are immutable.

Why this answer

(str) is correct because strings in Python are immutable sequences of Unicode code points. Once a string object is created, its contents cannot be changed; any operation that appears to modify a string (e.g., concatenation or slicing) actually creates a new string object in memory.

Exam trap

The PCAP exam often tests the distinction between bytes (immutable) and bytearray (mutable), expecting candidates to confuse the two because both deal with binary data.

5
MCQhard

What happens when you execute the following code? s = 'hello'; s[0] = 'H'

A.AttributeError is raised
B.TypeError is raised
C.String becomes 'Hello'
D.IndexError is raised
AnswerB

The operation `s[0] = 'H'` on a string invokes the sequence protocol's `__setitem__` method. Because `str` is an immutable type, it does not provide this mutator, so the interpreter raises `TypeError: 'str' object does not support item assignment`. This is Python's standard signal that the operation is unsupported for the given type, irrespective of the index value.

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] = 'H'`) raises a `TypeError`, not an `AttributeError` or `IndexError`, because the operation is a disallowed assignment on an immutable sequence type.

Exam trap

The PCAP exam often tests the distinction between `TypeError` and `AttributeError` in the context of immutable types, trapping candidates who confuse 'cannot assign' with 'method not found'.

How to eliminate wrong answers

Option A is wrong because `AttributeError` occurs when accessing a non-existent attribute or method on an object, not when attempting to modify an immutable object via indexing. Option C is wrong because strings are immutable; the assignment `s[0] = 'H'` does not modify the string in place, so 'hello' remains unchanged. Option D is wrong because `IndexError` is raised only when an index is out of range (e.g., `s[10]`), not when the index is valid but the assignment is disallowed due to immutability.

6
MCQhard

A junior developer is parsing a log file where each line has comma-separated fields. However, some fields are enclosed in double quotes and contain commas inside, e.g., '2023-08-15 14:30:00,WARNING,"Disk space low, please clean up".'. They are required to parse these lines using only built-in string methods (no modules like csv or re). Which approach is the most reliable and efficient?

A.Remove all double quotes from the line before splitting
B.Write a custom parser that iterates over characters, toggles a quote flag, and splits on commas when outside quotes
C.Use a regular expression that matches commas outside double quotes
D.Use the split() method and then merge fields that start with a double quote
AnswerB

A character-by-character parser tracking a quote flag splits only on commas outside quoted sections, correctly handling embedded commas within fields. Built-in string methods suffice, and it avoids the incorrect splits a naive comma split would produce, meeting the no-modules constraint.

Why this answer

A custom parser that toggles a quote flag while iterating over characters can reliably distinguish commas inside double quotes from field-separating commas. This approach handles embedded commas and escaped quotes without relying on external modules, making it both efficient and robust for the given constraints.

Exam trap

The trap here is that candidates often choose Option A (removing quotes) or Option D (split and merge) because they seem simpler, but they fail to realize that those methods break when commas appear inside quoted fields, which is the exact scenario the question describes.

How to eliminate wrong answers

Option A is wrong because removing all double quotes destroys the structure needed to identify which commas are inside quoted fields, leading to incorrect field splitting. Option C is wrong because the PCAP exam explicitly restricts the use of modules like `re` (regular expressions) for this task, and even if allowed, a regex for commas outside quotes is complex and error-prone with edge cases like escaped quotes. Option D is wrong because using `split()` and then merging fields that start with a double quote fails when a quoted field contains a comma that is not at the start of a split segment, and it cannot handle multiple quoted fields or fields with internal escaped quotes.

7
Drag & Dropmedium

Drag and drop the steps to handle an exception in Python using try-except-finally into the correct order.

Drag or tap steps into the slots.

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

Why this order

Exception handling follows the order: try block, except blocks, else block, finally block. The raise statement can be used anywhere to trigger an exception.

8
MCQhard

You are a network engineer troubleshooting a script that processes router configuration files. The script reads a configuration line from a file: 'interface GigabitEthernet0/1 ip address 192.168.1.1 255.255.255.0 no shutdown'. The script needs to extract the interface name and IP address. The current code uses string split operations but fails when the line has extra spaces or tabs. For example, when the line is 'interface GigabitEthernet0/1', the split returns ['interface', '', '', 'GigabitEthernet0/1'] and the script fails. You need to modify the script to robustly extract the interface name and IP address regardless of whitespace. Which approach should you take?

A.Manually iterate and concatenate characters until a space is found.
B.Use line.split() instead of line.split(' ').
C.Use line.split(' ') and then filter out empty strings.
D.Use line.startswith('interface') to identify the line, then extract substring.
AnswerB

Calling split() with no arguments (or None) splits on any sequence of whitespace—spaces, tabs, newlines—and automatically discards leading/trailing delimiters, so repeated spaces do not produce empty strings. For a line such as 'interface GigabitEthernet0/1' this returns ['interface', 'GigabitEthernet0/1'] with the interface name as the second token, regardless of how many spaces separate the words. This is the canonical, robust way to parse whitespace-delimited configuration output.

Why this answer

`line.split()` without arguments splits on any whitespace (spaces, tabs, newlines) and automatically removes empty strings, making it robust against extra spaces or tabs. In contrast, `line.split(' ')` splits only on single space characters, leaving empty strings when multiple spaces or tabs are present. This behavior is defined by Python's string method documentation and is essential for parsing configuration files where whitespace is inconsistent.

Exam trap

The trap here is that candidates often confuse `split()` with `split(' ')`, assuming they behave identically, but `split(' ')` only splits on a single space character and leaves empty strings for multiple spaces or tabs, while `split()` handles all whitespace and removes empties automatically.

How to eliminate wrong answers

Option A is wrong because manually iterating and concatenating characters until a space is found is inefficient, error-prone, and reinvents a built-in function that already handles arbitrary whitespace correctly. Option C is wrong because using `line.split(' ')` and then filtering out empty strings still fails when tabs are present, as `split(' ')` does not split on tabs; it would treat a tab as part of the string, leading to incorrect extraction. Option D is wrong because `line.startswith('interface')` only identifies the line type but does not extract the interface name or IP address; it would require additional parsing steps and does not solve the whitespace problem.

9
MCQmedium

What is the cause of the error?

A.The error is because `encode` returns a string, but the plus operator expects two strings.
B.The `username` variable is of type bytes, so encoding is unnecessary.
C.The result of `username.encode('utf-8')` is bytes, and Python does not allow concatenating str with bytes.
D.The encode method is called incorrectly; it should be `username.encode()` without argument.
AnswerC

In Python, `str.encode('utf-8')` transforms the text into a sequence of bytes. The `+` operator between a `str` and a `bytes` object is undefined because the two types represent different kinds of data—human-readable text versus raw binary. Python raises a `TypeError` to avoid ambiguous implicit conversions, requiring the programmer to explicitly decode the `bytes` back to `str` or encode the other operand.

Why this answer

`username.encode('utf-8')` returns a bytes object, and Python's `+` operator does not allow concatenation of `str` and `bytes` types. This raises a `TypeError: can only concatenate str (not "bytes") to str` because the other operand in the concatenation is a string literal.

Exam trap

The PCAP exam often tests the distinction between `str` and `bytes` types in Python, and the trap here is that candidates mistakenly think `encode` returns a string or that the error is about the method call itself, rather than recognizing the type mismatch in concatenation.

How to eliminate wrong answers

Option A is wrong because `encode` returns bytes, not a string; the error is not about encode returning a string. Option B is wrong because if `username` is already bytes, calling `.encode()` would raise an `AttributeError` (bytes have no `encode` method), not a concatenation type error; the scenario assumes `username` is a string. Option D is wrong because calling `encode()` without an argument defaults to UTF-8, which is valid; the error is not due to missing argument but due to type mismatch in concatenation.

10
MCQeasy

Consider the following code: print(type('apple,banana,cherry'.split(','))) What type of value is printed?

A.list
B.tuple
C.string
D.dict
AnswerA

When you call split() on a string, Python parses the string and returns a list of substrings, using whitespace or a specified separator as the delimiter. This list is mutable, so you can modify, index, or iterate over it. For example, 'a,b'.split(',') yields the list ['a', 'b'].

Why this answer

The `split()` method of a string returns a list of substrings. Thus, `type()` on that result returns `<class 'list'>`, indicating that the value is a list.

Exam trap

Candidates may incorrectly think that `split()` returns a tuple or that the type of a list literal is printed as 'list' due to confusion with brackets. However, `split()` always returns a list, so `type()` outputs `<class 'list'>`.

How to eliminate wrong answers

Option B is wrong because a tuple is defined with parentheses `()` or without brackets for a single-element tuple, not square brackets. Option C is wrong because a string is enclosed in quotes `''` or `""`, not square brackets. Option D is wrong because a dictionary is defined with curly braces `{}` and key-value pairs, not square brackets.

11
MCQmedium

A log processing script receives a multiline string log. The script needs to check if the string ends with the substring 'ERROR'. Which method should be used?

A.log.find('ERROR') != -1
B.log.rfind('ERROR') == len(log)-5
C.'ERROR' in log
D.log.endswith('ERROR')
AnswerD

The str.endswith('ERROR') method is the idiomatic and precise way to test whether a string ends with the given suffix. It performs a direct comparison of the final characters and returns True only if the last five characters are exactly 'ERROR', with no need for manual indexing or length arithmetic. This is the clear, readable solution that handles trailing content correctly and is the standard approach in Python.

Why this answer

The `endswith()` method is specifically designed to check if a string ends with a given substring. It returns `True` if the string ends with 'ERROR', making it the most direct and readable solution for this requirement.

Exam trap

The PCAP exam often tests the distinction between checking substring presence anywhere versus at a specific position, and candidates mistakenly choose `in` or `find` because they think 'checking if it ends with' is equivalent to 'checking if it contains'.

How to eliminate wrong answers

Option A is wrong because `log.find('ERROR') != -1` checks if 'ERROR' appears anywhere in the string, not specifically at the end. Option B is wrong because `log.rfind('ERROR') == len(log)-5` assumes 'ERROR' is exactly 5 characters and that the last occurrence is at the end, but this fails if 'ERROR' appears multiple times or if the string has trailing whitespace or newline characters. Option C is wrong because `'ERROR' in log` checks for substring presence anywhere, not exclusively at the end.

12
MCQhard

You are a developer at a company that processes customer feedback. Each feedback entry is stored as a string containing a rating (1-5) followed by a colon and then the comment. For example: '4: Great service'. You need to extract only the comments from feedback that have a rating of 4 or 5. You have a list of feedback strings. Which code snippet correctly implements this?

A.[s for s in feedback if s.startswith('4') or s.startswith('5')]
B.[s.split(':') for s in feedback][1]
C.[s.split(':')[1].strip() for s in feedback if s.split(':')[0].strip() in ('4','5')]
D.[s.split(':')[1] for s in feedback if '4' in s or '5' in s]
AnswerC

This is correct because it first splits the feedback string at the colon, strips whitespace from both the rating and comment, and only keeps the comment when the rating is exactly '4' or '5'. The condition uses a tuple membership test on the stripped first part, avoiding false positives from comments that merely contain the digit. It cleanly returns the comment portion, which is exactly what the requirement asks for.

Why this answer

It splits each feedback string on ':', extracts the comment (index [1]), strips whitespace, and filters only those entries where the rating (index [0], stripped) is exactly '4' or '5'. This ensures only comments from high-rated feedback are collected, handling potential spaces around the colon.

Exam trap

Python Institute often tests the difference between substring matching (using 'in') and exact prefix matching (using startswith or split-based comparison), leading candidates to choose Option D because they overlook that '4' or '5' could appear anywhere in the string, not just as the rating.

How to eliminate wrong answers

Option A is wrong because it selects the entire feedback string (including rating and colon) rather than extracting just the comment, and it uses startswith('4') or startswith('5') which would incorrectly match ratings like '45' or comments starting with those digits. Option B is wrong because it attempts to index the list comprehension result with [1], which is invalid syntax and would raise a TypeError; it also does not filter by rating. Option D is wrong because it uses the 'in' operator to check if '4' or '5' appears anywhere in the string, which would match comments containing those digits (e.g., 'I gave 4 stars') and does not ensure the rating is exactly 4 or 5 at the start.

13
MCQeasy

What is the result of 'PyThon'.lower()?

A.'Python'
B.'python'
C.'PYTHON'
D.'pYTHON'
AnswerB

Calling lower() on the string 'Python' returns a brand new string object 'python' because the method transforms the single uppercase character 'P' into its lowercase counterpart 'p' while leaving the subsequent 'ython' unchanged since those characters have no uppercase forms. The result is exactly 'python', confirming that the method performs a case conversion rather than, say, a formatting or trimming operation. This is the canonical expected output of 'Python'.lower().

Why this answer

The `.lower()` method in Python returns a new string with all alphabetic characters converted to lowercase. Since the original string 'PyThon' contains uppercase 'P' and 'T', applying `.lower()` yields 'python'. Option B is correct because it is the only option that shows all characters in lowercase.

Exam trap

Python Institute often tests the distinction between `.lower()`, `.upper()`, `.capitalize()`, and `.swapcase()`, so the trap here is that candidates may confuse `.lower()` with `.capitalize()` (which only lowercases the rest after capitalizing the first letter) or assume `.lower()` only affects the first letter.

How to eliminate wrong answers

Option A is wrong because 'Python' retains the uppercase 'P', which would only result from a method like `.capitalize()` or no transformation at all. Option C is wrong because 'PYTHON' is entirely uppercase, which would be produced by `.upper()`, not `.lower()`. Option D is wrong because 'pYTHON' has a lowercase 'p' but uppercase 'YTHON', which is not the result of `.lower()`; it might be confused with a swapcase or manual transformation.

14
MCQhard

A data pipeline processes CSV lines that may contain quoted fields with commas inside double quotes. For example: 'John, "Doe, Jr.", 35'. The team needs to split such a line correctly. Which approach is best?

A.Manually iterate over characters and track quote state.
B.Use str.split(',') after removing all quotes.
C.Use csv.reader([line]) to parse the line.
D.Use re.split(r',(?=(?:[^"]*"[^"]*")*[^"]*$)', line)
AnswerC

csv.reader([line]) is the correct approach because csv.reader is a full CSV parser implementing the quoting rules (RFC 4180 and the dialect parameters such as quotechar, doublequote, escapechar, and delimiter). By passing [line] — a one-element list, not the raw string — you fulfill csv.reader's expectation of an iterable of lines, and it returns a single parsed row as a list of fields. It correctly handles commas embedded inside quoted fields, escaped double quotes ("" inside a quoted field), and quoted fields with surrounding whitespace, all without manual parsing or brittle regular expressions. This is exactly the kind of robust, tested behavior the Python standard library provides for CSV data.

Why this answer

Python's `csv.reader` is specifically designed to handle CSV parsing according to RFC 4180, including quoted fields that contain commas, newlines, and embedded quotes. It automatically manages quote state and field boundaries, making it the most robust and Pythonic solution for this task.

Exam trap

Python Institute often tests the misconception that regex or manual string splitting is sufficient for CSV parsing, when in fact the `csv` module is the standard library solution that correctly handles all edge cases defined by the CSV format specification.

How to eliminate wrong answers

Option A is wrong because manually iterating over characters and tracking quote state is error-prone, reinvents the wheel, and violates the principle of using built-in libraries for standard formats. Option B is wrong because removing all quotes before splitting destroys the structure of quoted fields (e.g., 'Doe, Jr.' becomes 'Doe, Jr.' and then splits incorrectly on the comma inside). Option D is wrong because the regex pattern, while attempting to match commas outside quotes, is fragile and fails on edge cases like escaped quotes, uneven quote counts, or empty quoted fields; it also has poor performance on large files.

15
MCQeasy

What is the result of the expression 'Hello' * 3?

A.'Hello3'
B.'HelloHelloHello'
C.'Hello Hello Hello'
D.TypeError
AnswerB

In Python, the asterisk operator, when applied to a string and an integer, repeats the string the specified number of times. So 'Hello' * 3 evaluates to 'HelloHelloHello' by concatenating three identical copies of the original string in sequence. This is a core feature of sequence types, and the result is always a single new string of length equal to the original length multiplied by the integer.

Why this answer

In Python, the multiplication operator (*) on a string repeats the string a specified number of times. 'Hello' * 3 concatenates 'Hello' three times, producing 'HelloHelloHello'. This is a fundamental string operation defined in Python's sequence protocol.

Exam trap

The Python Institute often tests the distinction between string repetition (*) and string concatenation (+), and the trap here is that candidates may incorrectly assume spaces are added or that an error occurs when multiplying a string by an integer.

How to eliminate wrong answers

Option A is wrong because it suggests string concatenation with a number, which would require explicit conversion (str(3)) and does not occur with the * operator. Option C is wrong because it implies spaces are inserted between repetitions, but the * operator performs concatenation without any separator. Option D is wrong because multiplying a string by an integer is a valid operation in Python, not a TypeError.

16
Multi-Selectmedium

Which THREE of the following string methods return a boolean value (True or False)? (Choose exactly 3 correct answers.)

Select 3 answers
A.isspace()
B.isalpha()
C.isdigit()
D.replace()
E.find()
AnswersA, B, C

isspace() is a string predicate method that returns True only when the string is non-empty and every character in it is classified as whitespace by Python, including the space character, tab '\t', newline '\n', carriage return '\r', and other Unicode whitespace characters. Because it performs a character-by-character truth check and produces a boolean result, it is one of the valid answers to this question.

Why this answer

The `isspace()` method returns `True` if all characters in the string are whitespace characters (e.g., space, tab, newline) and the string is non-empty; otherwise, it returns `False`. This is a boolean-returning method that checks a specific character property, making option A correct.

Exam trap

Python Institute often tests the distinction between methods that return a boolean versus those that return an integer or a new string, and the trap here is that candidates confuse `find()` (returns index) with `in` operator (returns boolean) or assume `replace()` returns a boolean because it modifies the string in some contexts.

17
MCQeasy

Which of the following is the BEST practice for building a large string by concatenating many smaller strings in Python?

A.result = ''.join(parts)
B.result = sum(parts, '')
C.result = str.concat(*parts)
D.result = ''; for part in parts: result += part
AnswerA

''.join(parts) is the canonical and most efficient way to combine a sequence of strings in Python. It allocates exactly one new string object, iterates over parts once, and copies each part's characters into a pre-sized buffer, achieving O(n) time and minimal memory overhead. This method clearly communicates intent and avoids the quadratic behavior of repeated concatenation.

Why this answer

`''.join(parts)` is the most efficient way to concatenate a large number of strings in Python. It allocates memory once for the final string by iterating over the list and copying each part into the result buffer, avoiding the O(n²) time complexity of repeated concatenation in a loop.

Exam trap

Python Institute often tests the misconception that `+=` is acceptable for all string building, or that `sum` or non-existent methods like `str.concat` are valid, when in fact `''.join()` is the only efficient and correct approach for large concatenations.

How to eliminate wrong answers

Option B is wrong because `sum(parts, '')` is not intended for string concatenation; it performs addition with a start value of an empty string, which raises a TypeError because `sum` expects numeric types by default and does not support string concatenation. Option C is wrong because `str.concat(*parts)` is not a valid Python built-in method; there is no `str.concat` function, and this would raise an AttributeError. Option D is wrong because using `result += part` in a loop creates a new string object for each iteration, leading to O(n²) time complexity due to repeated memory allocation and copying, making it inefficient for large numbers of parts.

18
MCQmedium

Refer to the exhibit. Which of the following fixes the error?

A.print('Hello' + '5')
B.print('Hello' + str(5))
C.Both A and B
D.print('Hello' * 5)
AnswerC

Both A and B produce the intended output without error. Option A uses direct string concatenation with a string literal, while option B uses explicit conversion of the integer to a string. Neither causes a TypeError, so both fix the error described in the exhibit.

Why this answer

Both A and B produce the string 'Hello5' without error. In Python, the + operator concatenates strings, so 'Hello' + '5' works. Option B converts the integer 5 to a string using str() before concatenation, which also works.

Option D uses the * operator to repeat the string 'Hello' five times, producing 'HelloHelloHelloHelloHello', which is a valid operation but does not fix the error described in the exhibit (likely a TypeError from trying to concatenate a string and an integer).

Exam trap

Python Institute often tests the distinction between implicit type conversion (which Python does not do for string+int) and explicit conversion using str(), and candidates may forget that string repetition with * is valid but does not solve a concatenation error.

How to eliminate wrong answers

Option A is wrong because it is actually correct—it concatenates two strings without error, so it does fix the error. Option B is wrong because it is also correct—it converts the integer to a string before concatenation, fixing the error. Option D is wrong because while it is a valid Python expression, it repeats the string 'Hello' five times rather than concatenating it with 5, so it does not address the specific error of concatenating a string and an integer.

19
Multi-Selectmedium

Which TWO statements are true regarding strings in Python?

Select 2 answers
A.Strings can be concatenated with the + operator.
B.Strings are not sequences.
C.Strings are mutable.
D.Strings can be repeated with the * operator.
E.Strings do not support indexing.
AnswersA, D

The + operator performs concatenation by creating a brand-new str object whose contents are the characters of the left operand followed by those of the right operand. For example, 'py' + 'thon' evaluates to 'python'. This operation does not modify either input string, which is consistent with string immutability, and it requires both operands to be of type str; attempting to concatenate a string with an int raises a TypeError.

Why this answer

Strings in Python support concatenation using the + operator, which joins two or more strings into a single string. This is a fundamental operation for combining textual data, and it works by creating a new string object that contains the characters from both operands in sequence.

Exam trap

Python Institute often tests the immutability of strings by presenting mutable-like operations (e.g., 's[0] = 'a'') as valid, and the trap here is that candidates confuse strings with lists, assuming strings can be modified in place like mutable sequences.

20
MCQmedium

A data analyst is cleaning a CSV file. They have a string variable containing a row of data: 'John,Doe,30,New York'. They need to extract the last name 'Doe' using string methods. The analyst writes: name = row.split(',')[1]. However, they are concerned about performance because the file contains millions of rows. They want to use a more efficient method that extracts the substring without creating a full list. Which approach should the analyst use?

A.Use split(',', 2) and take the second element
B.Use partition(',') and get the third element
C.Use rsplit(',', 1) and take the first part
D.Use string slicing after finding the comma positions: start = row.find(',')+1; end = row.find(',', start); name = row[start:end]
AnswerD

This technique directly extracts the substring between the first and second commas using index arithmetic. `row.find(',')` returns the index of the first comma, so adding 1 gives the character position immediately after it; then `row.find(',', start)` scans forward from that position to locate the second comma. Slicing `row[start:end]` copies only the needed characters and avoids creating a list of all fields, making it both memory-efficient and precise for this fixed-position CSV pattern.

Why this answer

It avoids creating a full list of all fields by using `find()` to locate the comma positions and then slicing the substring directly. This approach is more memory-efficient for millions of rows, as it only extracts the required portion without splitting the entire string into a list.

Exam trap

A common trap in PCAP is thinking that any split() variant is always the best approach, ignoring the memory overhead of list creation in performance-critical scenarios.

How to eliminate wrong answers

Option A is wrong because `split(',', 2)` still creates a list of up to 3 elements, which is more efficient than a full split but still allocates a list object for each row. Option B is wrong because `partition(',')` returns a tuple of three strings (before, separator, after), but the third element is the remainder after the first comma, not the last name; to get 'Doe', you would need the second element (the part between the first and second commas), which is not directly provided. Option C is wrong because `rsplit(',', 1)` splits from the right, returning a list of two elements where the first part is everything before the last comma, which would be 'John,Doe,30' — not the last name.

21
MCQmedium

A developer writes code to display a floating-point number with exactly two decimal places. Which f-string expression is correct for value = 3.14159?

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

This is the correct f-string format specifier: the dot ('.') introduces a precision field, '2' is the number of digits to display after the decimal point, and 'f' selects fixed-point notation. For example, f"{3.14159:.2f}" evaluates to '3.14', and Python automatically rounds the value to the requested precision. This matches the requirement to display exactly two decimal places, making it the only valid option among the choices.

Why this answer

The format specifier `.2f` in an f-string explicitly instructs Python to format the floating-point number with exactly two digits after the decimal point. The `f` type ensures fixed-point notation, and the precision `.2` controls the number of decimal places. This is the standard way to achieve two-decimal-place output for a float in Python.

Exam trap

Python exams often test the distinction between width and precision in format specifiers, trapping candidates who confuse `0.2` (width.precision without type) with `.2f` (precision with float type), or who mistakenly use `%` syntax from older Python formatting styles.

How to eliminate wrong answers

Option A is wrong because `0.2` is a width-and-precision specifier without a type code; it pads the number to a total width of 2 characters (including the decimal point) but does not guarantee two decimal places, and for `3.14159` it would produce `3.14159` (no truncation) or cause unexpected behavior. Option C is wrong because `%2f` is not a valid format specifier; the `%` character is used for old-style `%` formatting, not f-string syntax, and `2f` is misinterpreted. Option D is wrong because `2f` lacks a decimal point before the precision; it sets a minimum field width of 2 but does not specify decimal places, so it would output the full float without truncation (e.g., `3.14159`).

22
MCQmedium

A developer wants to replace all vowels in a string with their corresponding uppercase letters. They wrote: `s = 'hello world'`; `vowels = 'aeiou'`; `trans = str.maketrans(vowels, vowels.upper())`; `result = s.translate(trans)`. What is the value of `result`?

A.'HEllO WOrld'
B.'hEllO wOrld'
C.'H@ll@ W@rld'
D.'hello world'
AnswerB

In 'hEllO wOrld', each vowel from the original 'hello world' has been changed to its uppercase counterpart: 'e' becomes 'E' and every 'o' becomes 'O' ('hello' becomes 'hEllO' and 'world' becomes 'wOrld'). All consonants ('h', 'l', 'w', 'r', 'd') remain lowercase exactly as they appeared in the input. This aligns perfectly with the requirement to replace all vowels without touching non-vowels.

Why this answer

The `str.maketrans(vowels, vowels.upper())` creates a translation table mapping each lowercase vowel to its uppercase equivalent. The `translate()` method then replaces only the vowels in the original string, leaving all other characters unchanged. In 'hello world', the vowels 'e', 'o', 'o' become 'E', 'O', 'O', resulting in 'hEllO wOrld' — note that the first 'h' and 'w' remain lowercase because they are consonants.

Exam trap

Python Institute often tests the distinction between `str.maketrans()` and `str.replace()`, and the trap here is that candidates mistakenly think all letters are affected or that the mapping applies to consonants, when in fact only the specified characters (vowels) are transformed.

How to eliminate wrong answers

Option A is wrong because it incorrectly capitalizes the first 'h' and 'w', which are not vowels and should remain lowercase. Option C is wrong because it replaces vowels with '@' symbols, which would only happen if the translation table mapped vowels to '@' instead of uppercase letters. Option D is wrong because it shows the original unchanged string, ignoring the vowel-to-uppercase mapping entirely.

23
MCQeasy

A programmer wants to check whether a string `s` is a palindrome (reads the same forwards and backwards, ignoring case and non-alphanumeric characters). Which code snippet correctly implements this?

A.s.lower() == s.lower()[::-1]
B.clean = ''.join(c for c in s if c.isalnum()); return clean.lower() == clean.lower()[::-1]
C.s == s[::-1]
D.return s.lower() == ''.join(reversed(s.lower()))
AnswerB

This solution first constructs a cleaned string by joining only characters that satisfy isalnum(), effectively stripping spaces, punctuation, and symbols. After converting that filtered result to lowercase via .lower(), it compares it to its own reversed slice [::-1]. This correctly handles case-insensitivity and ignores all non-alphanumeric characters, making it a robust and idiomatic palindrome check.

Why this answer

It first filters out non-alphanumeric characters using `c.isalnum()`, then converts the cleaned string to lowercase before comparing it with its reverse via slicing `[::-1]`. This ensures that case differences and punctuation/spaces are ignored, which is required for a proper palindrome check per the problem statement.

Exam trap

Python Institute often tests the candidate's understanding that a simple case-insensitive comparison is insufficient; the trap is that many candidates forget to remove non-alphanumeric characters, leading them to pick Option A or D, which only handle case but not punctuation or spaces.

How to eliminate wrong answers

Option A is wrong because it only converts the original string to lowercase and compares it to its reverse, but it does not remove non-alphanumeric characters (e.g., spaces, punctuation), so strings like 'A man, a plan, a canal, Panama' would incorrectly fail. Option C is wrong because it compares the raw string with its reverse without any case normalization or character filtering, so it will fail for any mixed-case or non-alphanumeric input. Option D is wrong because it converts the original string to lowercase and uses `reversed()` to compare, but it does not strip non-alphanumeric characters, leading to false negatives for strings containing spaces or punctuation.

24
MCQeasy

A function receives a file path like '/home/user/docs/file.txt' and needs to return the path without the file extension, e.g., '/home/user/docs/file'. Which code reliably removes only the last dot extension, even if the directory names contain dots?

A.path.split('.')[0]
B.path.rsplit('.', 1)[0]
C.path.replace('.', '', 1)
D.path[:path.find('.')]
AnswerB

path.rsplit('.', 1) splits from the right side using a maxsplit of 1, so it stops after encountering the last dot in the string, and [0] gives the substring before that final dot. This correctly removes only the extension from a path such as '/home/user/file.txt', producing '/home/user/file' while preserving any dots in the directory path, as with '/home/user.name/file.txt' -> '/home/user.name/file'. It is the string-method idiom for stripping a trailing extension, although os.path.splitext is the more robust alternative in practice.

Why this answer

`rsplit('.', 1)` splits the string from the right, limiting the split to exactly one occurrence, which isolates the file extension (the part after the last dot) and returns everything before it. This reliably removes only the last dot extension, even if directory names contain dots, because it targets the final dot in the path.

Exam trap

The Python PCAP exam often tests the distinction between `split` and `rsplit` with the maxsplit parameter, and the trap here is that candidates mistakenly use `split('.')[0]` or `path[:path.find('.')]`, which fail when directory names contain dots because they target the first dot instead of the last.

How to eliminate wrong answers

Option A is wrong because `split('.')` splits on every dot in the path, returning a list of all segments; taking index `[0]` only gives the part before the first dot, which would incorrectly truncate the path at the first dot (e.g., '/home/user/docs' from '/home/user/docs/file.txt' becomes '/home/user/docs' instead of '/home/user/docs/file'). Option C is wrong because `replace('.', '', 1)` replaces only the first occurrence of a dot, which would remove the dot in a directory name (e.g., 'docs' in '/home/user/docs/file.txt' becomes '/home/user/docsfile.txt') rather than the extension dot. Option D is wrong because `path[:path.find('.')]` finds the index of the first dot and slices up to it, which again truncates at the first dot and fails if directory names contain dots (e.g., '/home/user/docs/file.txt' becomes '/home/user/docs').

25
MCQhard

You are developing a high-performance logging module that must handle thousands of log entries per second. Each entry is built by concatenating a timestamp, level, and message. Currently, your code uses a loop that repeatedly appends to a string using the += operator. This results in high memory usage and sluggish performance because each concatenation creates a new string object. The module must run on systems with limited memory and cannot rely on external libraries. Which course of action would best resolve the performance issue while maintaining readability and standard library compliance?

A.Collect the string parts in a list and use str.join() to combine them at the end.
B.Use string formatting (f-strings or format) within the loop to build the log entry.
C.Write the log entries directly to a file using file.write() in the loop.
D.Continue using += but preallocate a large string buffer using array.array or io.StringIO to reduce reallocation.
AnswerA

Accumulating fragments in a list and calling str.join() only at the end is efficient because Python can first calculate the total length of the combined result, allocate a single string buffer exactly once, and then copy each fragment into place. This avoids the O(n²) copying behavior of repeated concatenation, where each += operation allocates a new string and copies all previous content. For logging modules that assemble many small parts per entry, this is the recommended Pythonic pattern.

Why this answer

Collecting string parts in a list and using str.join() avoids repeated string concatenation, which creates a new string object for each += operation. This approach reduces memory allocation overhead and improves performance, especially under high throughput, while remaining fully compliant with standard library constraints.

Exam trap

Python Institute often tests the misconception that string formatting (f-strings) or incremental I/O (file.write) avoids the immutability penalty, when in fact they still create new string objects or introduce I/O latency, respectively.

How to eliminate wrong answers

Option B is wrong because using f-strings or format() inside the loop still creates a new string object per iteration, incurring the same memory and performance penalty as +=. Option C is wrong because writing directly to a file in the loop introduces I/O overhead for each log entry, which is slower than batching writes and may cause excessive disk writes under high load. Option D is wrong because preallocating a buffer with array.array or io.StringIO does not eliminate the fundamental issue of repeated string concatenation; io.StringIO is designed for incremental building but still involves internal reallocation, and array.array is not intended for string concatenation, leading to complexity and potential type errors.

26
Multi-Selecteasy

Which TWO string methods are used to determine if a string begins or ends with a specified prefix or suffix? (Choose two.)

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

startswith() is the correct method for a prefix check: it returns True only when the string's beginning exactly matches the specified prefix, and False otherwise. It also accepts a tuple of possible prefixes, as well as optional start and end indices for slicing-like boundaries, making it both expressive and efficient. Because it directly answers 'does this string begin with...?', it is one of the two required methods.

Why this answer

The `startswith()` method returns `True` if a string begins with the specified prefix, and `endswith()` returns `True` if a string ends with the specified suffix. Both methods accept a string or a tuple of strings to check against, making them the correct choices for determining prefix or suffix presence.

Exam trap

The PCAP exam often tests the distinction between methods that return indices (`find()`, `index()`) versus methods that return booleans (`startswith()`, `endswith()`), and candidates mistakenly choose `find()` or `index()` because they think returning 0 for a prefix match is equivalent to a boolean check.

27
MCQhard

A script reads a binary file and decodes it as UTF-8. Some bytes are invalid UTF-8 sequences, causing a `UnicodeDecodeError`. The developer wants to replace invalid bytes with the replacement character U+FFFD. Which approach achieves this?

A.data.decode('utf-8', errors='strict')
B.data.decode('utf-8', errors='surrogateescape')
C.data.decode('utf-8', errors='replace')
D.data.decode('utf-8', errors='ignore')
AnswerC

The replace handler maps each invalid byte or byte sequence to the Unicode replacement character U+FFFD, yielding a valid, displayable string that clearly marks where decoding errors occurred. This is the correct choice because the script likely needs to render the text content without crashing, while still indicating corrupted or non-UTF-8 portions. It sacrifices the original byte values but maintains the overall structure and length approximation of the data.

Why this answer

The `errors='replace'` parameter in Python's `decode()` method replaces any bytes that cannot be decoded as valid UTF-8 with the Unicode replacement character U+FFFD, which is exactly what the developer wants. This approach ensures the script continues processing without raising a `UnicodeDecodeError` while preserving the overall structure of the data.

Exam trap

Python Institute often tests the distinction between `errors='replace'` and `errors='ignore'`, where candidates mistakenly choose 'ignore' thinking it handles errors gracefully, but the trap is that 'ignore' silently drops invalid bytes instead of inserting a visible placeholder, which can lead to unintended data concatenation or loss of positional alignment.

How to eliminate wrong answers

Option A is wrong because `errors='strict'` is the default behavior that raises a `UnicodeDecodeError` on invalid UTF-8 sequences, which the developer explicitly wants to avoid. Option B is wrong because `errors='surrogateescape'` replaces invalid bytes with surrogate code points (U+DC80–U+DCFF) rather than the replacement character U+FFFD, which is intended for round-tripping binary data through strings, not for producing clean Unicode output. Option D is wrong because `errors='ignore'` silently removes invalid bytes without any replacement, which can corrupt the data stream and lose information, whereas the developer wants to replace invalid bytes with a visible placeholder.

28
MCQhard

A Python script reads a file containing text with non-ASCII characters like 'é' and 'ü'. The script must encode the string as UTF-8 then decode it back. Which of the following correctly handles this without error?

A.s.decode('utf-8').encode('utf-8')
B.s.encode('ascii').decode('ascii')
C.s.encode('utf-8').decode('utf-8')
D.s.decode('utf-8').decode('utf-8')
AnswerC

This is the correct round-trip: s.encode('utf-8') serializes the Unicode string into a bytes object using UTF-8's variable-length encoding, and .decode('utf-8') deserializes those exact bytes back into the original str. Because UTF-8 can encode every Unicode code point, the transformation is lossless and the resulting string is equal to s. Unlike the wrong options, it respects the proper direction (str → bytes → str) and never applies decode to a str. This pattern is commonly used when passing text through byte-oriented APIs or verifying byte-level round-trippability.

Why this answer

It first encodes the string (which contains non-ASCII characters like 'é' and 'ü') into UTF-8 bytes using `.encode('utf-8')`, then decodes those bytes back into a string using `.decode('utf-8')`. This round-trip preserves all characters since UTF-8 can represent any Unicode code point, and the operations are applied in the correct order: a string is encoded to bytes, then bytes are decoded back to a string.

Exam trap

Python Institute often tests the distinction between string and bytes methods — the trap here is that candidates confuse `.encode()` and `.decode()`, thinking both can be called on strings, or they incorrectly assume ASCII can handle non-ASCII characters without error.

How to eliminate wrong answers

Option A is wrong because it attempts to decode a string (which is already a Unicode object) using `.decode('utf-8')`, which raises an `AttributeError` — decode is a method of bytes, not str. Option B is wrong because it encodes the string to ASCII, which will raise a `UnicodeEncodeError` for non-ASCII characters like 'é' and 'ü' since ASCII only supports code points 0–127. Option D is wrong because it calls `.decode()` twice on a string, which is invalid for the same reason as Option A — the first decode fails, and even if it were bytes, double decoding would produce garbage or an error.

29
MCQeasy

A developer wants to check if a string 'example.txt' ends with '.txt'. Which expression returns True?

A.'example.txt'.endswith('.txt')
B.'example.txt'.startswith('.txt')
C.'example.txt'.find('.txt')
D.'example.txt'.rsplit('.',1)
AnswerA

This is the correct choice because str.endswith() returns a boolean (True or False) after checking whether the string's final characters match the given suffix. Since 'example.txt' literally concludes with the four characters '.txt', the method evaluates to True, giving the developer an unambiguous and efficient way to verify the file extension. It is also case-sensitive and can accept a tuple of suffixes, but for this simple check it directly satisfies the requirement.

Why this answer

The `endswith()` method is specifically designed to check if a string ends with a given suffix. In this case, `'example.txt'.endswith('.txt')` returns `True` because the string ends with the substring '.txt'.

Exam trap

The PCAP exam often tests the distinction between methods that return boolean values (`endswith`, `startswith`) versus those that return indices (`find`, `index`) or lists (`split`, `rsplit`), leading candidates to pick options that perform a related operation but do not return `True`.

How to eliminate wrong answers

Option B is wrong because `startswith('.txt')` checks if the string begins with '.txt', not ends with it, so it returns `False`. Option C is wrong because `find('.txt')` returns the index of the first occurrence of '.txt' (which is 7) or -1 if not found, not a boolean value, so it does not return `True`. Option D is wrong because `rsplit('.',1)` splits the string from the right at the last dot, returning a list `['example', 'txt']`, not a boolean.

30
MCQhard

A team is using f-strings to format a report. They have a variable `value = 0.123456789` and want to display it with exactly 3 significant digits. They write `f"{value:.3g}"`. The output is '0.123'. They expected '0.123'. Is the output correct? If not, what change would produce '0.123'?

A.Use `f"{value:.3s}"`
B.Use `f"{value:.3f}"`
C.Use `f"{value:.3e}"`
D.The output is correct as is.
AnswerD

Correct—the format spec already in use (`.3g`) rounds to three significant digits and picks fixed-point notation for this magnitude. For `0.123456`, the three significant digits are 1, 2, and 3, and because the adjusted exponent is within the `g` threshold, it prints as `0.123` without an exponent. The output is exactly what the report requires, so no alternative specifier is needed.

Why this answer

The format specifier `.3g` in an f-string instructs Python to format the number with 3 significant digits using general format. For `0.123456789`, the first three significant digits are '123', and the general format automatically switches to fixed-point notation when the exponent is small, producing '0.123' exactly as expected.

Exam trap

The trap here is that candidates confuse 'significant digits' (controlled by `g`) with 'decimal places' (controlled by `f`), leading them to incorrectly choose `.3f` when `.3g` is the correct specifier for significant digits.

How to eliminate wrong answers

Option A is wrong because `s` is not a valid format type for numeric values; it is used for strings and would raise a ValueError. Option B is wrong because `.3f` formats with exactly 3 digits after the decimal point, which would produce '0.123' only by coincidence for this value, but it is not the correct approach for significant digits; for a value like 0.0012345, `.3f` would give '0.001' (only 1 significant digit), not 3. Option C is wrong because `.3e` forces scientific notation with 3 digits after the decimal point, producing '1.235e-01' (rounded), not '0.123'.

31
MCQmedium

A network engineer processes a configuration file containing MAC addresses in the format 'aa:bb:cc:dd:ee:ff'. They need to convert each MAC address into a 6-byte bytes object for use in packet crafting. The current code is: mac_bytes = bytes([int(x, 16) for x in mac_str.split(':')]). This works correctly, but they need to process thousands of MAC addresses and want to optimize performance. They also need to handle invalid MAC addresses (e.g., non-hex characters) without crashing. Which of the following approaches is the most efficient and robust?

A.Use the same list comprehension but add a try-except block for ValueError
B.Use bytes.fromhex(mac_str.replace(':', ''))
C.Use struct.pack('BBBBBB', *[int(x,16) for x in mac_str.split(':')])
D.Use a for loop to parse each pair and build a bytearray
AnswerB

bytes.fromhex() is a built-in method implemented in C that parses a hex string directly into a bytes object, making it the fastest and most idiomatic choice. Removing the colons with .replace(':', '') yields a 12-character hex string, which fromhex converts to exactly six bytes. It also performs validation in the C layer: non-hex characters or odd-length strings raise ValueError, giving the same error behavior as a manual parse but without Python-level iteration.

Why this answer

`bytes.fromhex()` is implemented in C, making it significantly faster than a Python-level list comprehension for thousands of conversions. It also inherently validates that the input contains only hexadecimal characters (and colons, which are ignored after removal), raising a `ValueError` for invalid input, which can be caught for robustness. This approach avoids the overhead of splitting, iterating, and calling `int()` for each octet.

Exam trap

The PCAP exam often tests the misconception that a list comprehension or `struct.pack` is the most efficient approach, when in reality Python's built-in `bytes.fromhex()` leverages C-level optimization for both speed and validation.

How to eliminate wrong answers

Option A is wrong because while it adds error handling, it still uses the slower list comprehension with `int(x, 16)` for each octet, which involves Python-level iteration and function calls, making it less efficient than the C-level `bytes.fromhex()`. Option C is wrong because `struct.pack()` adds unnecessary overhead by requiring the list comprehension to produce the integers first, then packing them into bytes; it is neither the most efficient nor the most direct method. Option D is wrong because a manual for loop with `bytearray` is the slowest approach, as it involves Python-level iteration, multiple function calls, and incremental appending, which is far less efficient than the single C-level call in Option B.

32
MCQmedium

A developer generates a report where numbers must be right-aligned in a 10-character column using f-strings: f'{value:>10}'. However, some values may be None, causing a TypeError. Which is the most robust way to handle None values without affecting other falsy values like 0?

A.Use str.format() with a conditional for the format spec
B.f'{value or "N/A":>10}'
C.f'{value if value is not None else "N/A":>10}'
D.Wrap the f-string in a try-except block
AnswerC

This option uses a conditional expression that explicitly tests identity with `is not None`, meaning only `None` triggers the fallback while preserving all other values, including 0 and empty strings. The f-string then applies the `:>10` format spec to the selected result, right-aligning either 'N/A' or the numeric value in a 10-character field. It is the only choice that correctly distinguishes a missing sentinel from legitimate falsy data.

Why this answer

It uses an explicit identity check (`value is not None`) to distinguish `None` from other falsy values like `0` or empty strings. This ensures that `0` is still right-aligned as a number, while `None` is replaced with the string `"N/A"` before formatting. The f-string then applies the `>10` alignment specifier to the resulting value.

Exam trap

The PCAP exam often tests the distinction between identity checks (`is None`) and truthiness checks (`or`, `if value`) to catch candidates who assume all falsy values should be treated equally, especially when `0` is a valid numeric value that must be preserved.

How to eliminate wrong answers

Option A is wrong because `str.format()` with a conditional for the format spec does not inherently handle `None` values; it would still raise a `TypeError` when trying to format `None` unless the conditional also replaces the value itself. Option B is wrong because `value or "N/A"` treats `0` (a falsy number) as `None`, incorrectly replacing it with `"N/A"` instead of preserving it for right-alignment. Option D is wrong because wrapping the f-string in a `try-except` block is a reactive approach that catches the `TypeError` at runtime, but it is less robust and less readable than a proactive conditional check; it also requires additional logic to decide what to display on exception.

33
MCQmedium

What does the expression 'hello world'.title() return?

A.'Hello World'
B.'HELLO WORLD'
C.'Hello world'
D.'hello World'
AnswerA

'Hello World' is the exact return value of 'hello world'.title(): the title() method scans the string and, for each whitespace-delimited word, converts its first character to uppercase while converting any remaining characters to lowercase. Since both original words are already lowercase, each word becomes capitalized, yielding 'Hello World'.

Why this answer

The `title()` method in Python returns a copy of the string where the first character of each word is converted to uppercase and all remaining characters are converted to lowercase. For the string 'hello world', this results in 'Hello World', making option A correct.

Exam trap

Python Institute often tests the distinction between `title()`, `capitalize()`, and `upper()` by presenting strings where only one word is capitalized, leading candidates to confuse the behavior of these methods.

How to eliminate wrong answers

Option B is wrong because `title()` does not convert all characters to uppercase; that would be the behavior of the `upper()` method. Option C is wrong because it only capitalizes the first word, which is what `capitalize()` does, not `title()`. Option D is wrong because it capitalizes only the second word, which is not how `title()` operates; `title()` capitalizes the first character of every word.

34
Matchingmedium

Match each string method to its purpose.

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

Concepts
Matches

Returns uppercase copy

Splits into list of substrings

Removes leading/trailing whitespace

Replaces occurrences of a substring

Returns index of first occurrence

Why these pairings

The correct matches are: .upper() converts to uppercase, .lower() converts to lowercase, .strip() removes leading/trailing whitespace. Common confusions include swapping .split() and .replace(), and confusing .replace() with .upper().

35
MCQhard

What is the value of matches?

A.['Alice', 'Bob']
B.['Alice']
C.['Alice', 'and', 'Bob', 'are', 'friends']
D.['Alice', 'Bob', 'friends']
AnswerA

This is correct because the regex pattern likely uses a character class such as [A-Z] to require an initial uppercase letter followed by word characters, and `re.findall()` returns every non-overlapping match in the string. Both 'Alice' and 'Bob' begin with uppercase letters and consist entirely of alphabetic characters, so they are the complete set of matching substrings. No other word in the input starts with an uppercase letter, so no additional tokens qualify.

Why this answer

The `re.findall(r'[A-Z][a-z]*', 'Alice and Bob are friends')` call matches all sequences starting with an uppercase letter followed by zero or more lowercase letters. This yields 'Alice' and 'Bob', as they are the only words beginning with a capital letter. The result is a list of those two strings.

Exam trap

Python Institute often tests the misconception that `[a-z]*` matches any sequence of letters, but the pattern requires the first character to be uppercase, causing candidates to incorrectly include all words or miss the second capitalized word.

How to eliminate wrong answers

Option B is wrong because it omits 'Bob', which also starts with an uppercase 'B' and matches the pattern. Option C is wrong because it includes all words from the string, but the pattern only matches words starting with an uppercase letter, not lowercase words like 'and', 'are', 'friends'. Option D is wrong because it includes 'friends', which starts with a lowercase 'f' and does not match the pattern `[A-Z][a-z]*`.

36
Multi-Selectmedium

Which TWO of the following string methods return a new string with all characters converted to lowercase? (Select exactly two.)

Select 2 answers
A.str.title()
B.str.swapcase()
C.str.capitalize()
D.str.lower()
E.str.casefold()
AnswersD, E

str.lower() is a correct answer because it returns a new string in which every Unicode character that has a lowercase mapping is converted to its lowercase equivalent, while characters without a case mapping remain unchanged. This method performs a simple, one-to-one lowercase conversion that is sufficient for many case-insensitive comparisons and is the standard way to normalize text to lowercase.

Why this answer

Str.lower(), is correct because it returns a new string with all Unicode characters converted to lowercase according to the current locale's case mapping. Option E, str.casefold(), is correct because it returns a string suitable for case-insensitive comparisons by applying aggressive folding that handles special cases like the German 'ß' (which becomes 'ss'), going beyond simple lowercase conversion.

Exam trap

Python Institute often tests the distinction between str.lower() and str.casefold() by presenting both as correct answers, trapping candidates who think casefold() only does lowercase conversion, when in fact it performs a more aggressive Unicode folding that also results in a lowercase string.

37
Multi-Selectmedium

Which THREE of the following are true about Python strings?

Select 3 answers
A.They support slicing.
B.They are stored as arrays of ASCII characters.
C.They can be concatenated with the + operator.
D.They are mutable.
E.They support indexing.
AnswersA, C, E

Slicing is supported because strings are sequences: using the notation s[start:stop:step] you can extract a contiguous substring or even a reversed copy. The result is always a new string object, since the original cannot be modified in place, and the slice can use negative indices to count from the end, such as s[-3:] taking the last three characters.

Why this answer

Python strings are sequences, and the slicing syntax (e.g., s[start:stop:step]) allows extracting substrings by specifying indices. This works because strings implement the sequence protocol, including __getitem__ with slice objects.

Exam trap

Python Institute often tests the immutability of strings by presenting operations that appear to modify them in place, leading candidates to incorrectly select 'mutable' because they confuse string methods (like .replace() or .upper()) with in-place mutation.

38
MCQhard

What is the result of 'abcdef'[::-2]?

A.'dfb'
B.'ace'
C.'fdb'
D.'eca'
AnswerC

'fdb' is the correct result of the slice 'abcdef'[::-2]. The negative step tells Python to traverse the sequence backward from the last character, selecting 'f' (index 5), then 'd' (index 3), then 'b' (index 1). This is the only option that matches the requested backward, every-other-character behavior.

Why this answer

The slicing syntax [::-2] means start from the end (default step negative), go to the beginning, and take every second character in reverse order. For 'abcdef', starting at 'f' (index -1), then skipping one to 'd' (index -3), then 'b' (index -5), resulting in 'fdb'. Option C is correct.

Exam trap

Candidates often mistakenly think that [::-2] starts from the beginning and skips every two characters forward, leading them to pick 'ace' (option B) instead of understanding that a negative step reverses the traversal order.

How to eliminate wrong answers

Option A is wrong because 'dfb' would require a step of -2 starting from index -2 ('e'), which is not what [::-2] does. Option B is wrong because 'ace' is the result of a positive step of 2 from the beginning (i.e., 'abcdef'[::2]), not a negative step. Option D is wrong because 'eca' would be the result of reversing the string and then taking every second character from the start (i.e., 'fedcba'[::2]), which is a different operation.

39
MCQmedium

A developer needs to replace all occurrences of 'cat' with 'dog' in a string, but only if 'cat' is a whole word (not part of 'category'). Which code achieves this?

A.re.sub(r'\bcat\b', 'dog', s)
B.s.replace('cat', 'dog')
C.re.sub('cat', 'dog', s)
D.s.replace('cat', 'dog', 1)
AnswerA

The correct solution uses a raw-string regex pattern with word boundary anchors: `\b` at both ends ensures `cat` is only matched as a standalone word, not as a substring inside larger words like `category` or `bobcat`. `re.sub` then replaces every such whole-word occurrence globally, returning a new string with each standalone `cat` changed to `dog`, leaving all other text intact.

Why this answer

Uses the `re.sub()` function with the regex pattern `r'\bcat\b'`, where `\b` denotes a word boundary. This ensures that only the whole word 'cat' is matched and replaced with 'dog', ignoring cases where 'cat' appears as part of a larger word like 'category'. The `r` prefix makes it a raw string, preventing escape sequence issues.

Exam trap

Python Institute often tests the distinction between simple string methods and regex-based substitution, specifically the need for word boundary anchors (`\b`) to match whole words, which candidates overlook when they assume `replace()` or a plain `re.sub()` pattern is sufficient.

How to eliminate wrong answers

Option B is wrong because `s.replace('cat', 'dog')` performs a simple substring replacement, replacing every occurrence of 'cat' regardless of word boundaries, so 'category' would become 'dogegory'. Option C is wrong because `re.sub('cat', 'dog', s)` without word boundary anchors matches 'cat' anywhere in the string, including inside other words, leading to the same issue as Option B. Option D is wrong because `s.replace('cat', 'dog', 1)` replaces only the first occurrence of 'cat' (not all) and still does not respect word boundaries, so it fails both requirements.

40
MCQhard

A developer is working with a string `text = "The quick brown fox jumps over the lazy dog"`. They want to create a new string where every occurrence of the word 'the' (case-insensitive) is replaced with 'a'. However, they must not replace 'the' when it is part of another word, such as in 'then' or 'there'. Which approach correctly achieves this?

A.text.lower().replace('the', 'a')
B.import re; re.sub('the', 'a', text, flags=re.IGNORECASE)
C.import re; re.sub(r'\bthe\b', 'a', text, flags=re.IGNORECASE)
D.text.replace('the', 'a').replace('The', 'a')
AnswerC

The regular expression uses word boundaries (\b) to match 'the' only when it appears as a whole word. The re.IGNORECASE flag makes it case-insensitive, so 'The' and 'the' are both matched. This correctly replaces only the standalone word 'the' with 'a', leaving words like 'then' or 'there' unchanged. The result would be 'a quick brown fox jumps over a lazy dog' (with 'The' replaced by 'a' and 'the' replaced by 'a').

Why this answer

To replace a whole word case-insensitively, regular expressions with word boundaries are needed. The pattern \bthe\b matches 'the' only when it is a complete word, and the re.IGNORECASE flag makes it case-insensitive. The other methods either replace substrings within words, lose the original casing, or do not handle case variations properly.

The correct approach preserves the rest of the string and only substitutes standalone occurrences.

Exam trap

The trap here is assuming that simple string replace with case conversion or multiple replace calls can handle whole-word matching, when in fact word boundaries require regular expressions.

41
MCQeasy

A developer wants to convert a string 'Python' to all uppercase letters. Which string method should be used?

A.capitalize()
B.title()
C.swapcase()
D.upper()
AnswerD

The `str.upper()` method returns a new string with all alphabetic characters converted to uppercase, leaving non-alphabetic characters unchanged. For the string `'Python'`, it produces `'PYTHON'` without modifying the original string, satisfying the requirement for a non-destructive transformation. This method operates on each Unicode character’s case mapping, ensuring correct conversion for the given ASCII input.

Why this answer

The `upper()` method returns a copy of the string with all lowercase characters converted to uppercase. Since the goal is to convert 'Python' to 'PYTHON', `upper()` is the correct and most direct method for this task.

Exam trap

The Python PCAP exam often tests the distinction between `upper()` and `capitalize()` or `title()`, where candidates mistakenly choose `capitalize()` thinking it converts the entire string to uppercase, but it only capitalizes the first character.

How to eliminate wrong answers

Option A is wrong because `capitalize()` converts only the first character to uppercase and the rest to lowercase, resulting in 'Python' (no change) or 'python' if the string were all lowercase. Option B is wrong because `title()` capitalizes the first character of each word, which for a single word like 'Python' would produce 'Python' (no change) and is not designed for full uppercase conversion. Option C is wrong because `swapcase()` inverts the case of each character, turning 'Python' into 'pYTHON', not the desired all-uppercase result.

42
MCQeasy

A developer wants to create a string that contains the current year and month in the format 'YYYY-MM'. The year and month are stored in integer variables year and month. Which expression would produce the desired result?

A.f"{year}-{month:02d}"
B.year + '-' + month
C.str(year) + '-' + str(month)
D.'%s-%s' % (year, month)
AnswerA

The f-string `f"{year}-{month:02d}"` evaluates both expressions inline and applies a format specification to the month placeholder. The `02d` specifier instructs Python to format the integer month as a decimal with a minimum width of two characters, padding with a leading zero when needed. This produces the desired ISO-like format, e.g., `2024-03` for March.

Why this answer

Uses an f-string with the format specifier `:02d` to zero-pad the month to two digits, ensuring that months 1-9 appear as '01', '02', etc. This produces the exact 'YYYY-MM' format from integer variables without manual conversion or padding.

Exam trap

The PCAP exam often tests the distinction between string concatenation with `+` (which requires both operands to be strings) and f-string formatting, and the trap here is that candidates may forget to zero-pad the month, choosing Option C because it 'works' syntactically but fails the format requirement.

How to eliminate wrong answers

Option B is wrong because it attempts to concatenate integers directly with the `+` operator, which raises a `TypeError` in Python (cannot concatenate `int` and `str`). Option C is wrong because while it correctly converts both integers to strings, it does not zero-pad the month, so a month value of 3 would produce '2025-3' instead of '2025-03'. Option D is wrong because it uses old-style `%` formatting without a format specifier for zero-padding; `%s` simply converts the integer to a string without padding, yielding '2025-3' for month=3.

43
MCQeasy

What is the output of `print('-'.join(['a', 'b', 'c']))`?

A.a-b-c
B.['a', '-', 'b', '-', 'c']
C.('a', '-', 'b', '-', 'c')
D.a,b,c
AnswerA

The `str.join()` method returns a single string built by concatenating each element of the iterable with the given separator placed between them. Since the separator is '-' and the elements are 'a', 'b', and 'c', the correct printed output is the string `a-b-c`. The quotes are only part of the string literal in code, not part of the printed value, so the output has no brackets or extra characters.

Why this answer

The `join()` method in Python concatenates the elements of an iterable (here, a list of strings) into a single string, using the string on which it is called as the separator. In this case, `'-'.join(['a', 'b', 'c'])` inserts a hyphen between each element, producing the string `'a-b-c'`. The `print()` function then outputs that string without quotes.

Exam trap

Python Institute often tests whether candidates understand that `join()` returns a single string, not a list or tuple, and that the separator is placed between elements, not appended at the ends.

How to eliminate wrong answers

Option B is wrong because it shows a list `['a', '-', 'b', '-', 'c']`, which would be the result of incorrectly flattening the separator into the list rather than using `join()`. Option C is wrong because it shows a tuple `('a', '-', 'b', '-', 'c')`, which similarly misrepresents the output as a tuple of separate characters. Option D is wrong because `'a,b,c'` uses commas as separators, which would be produced by `','.join(['a', 'b', 'c'])`, not the hyphen separator specified in the question.

44
MCQhard

A cloud infrastructure engineer is developing a Python script to parse large configuration files from a fleet of servers. Each file can be up to 500 MB. The script reads the file line by line using a file object, strips comment lines (those starting with '#'), and accumulates only the configuration directives into a single string for further processing. The current code is: ```python result = '' with open('config.cfg') as f: for line in f: if not line.startswith('#'): result += line.strip() ``` After processing just a few hundred lines of a large file, the script becomes extremely slow and consumes an excessive amount of memory. The engineer identifies that string concatenation using `+=` is inefficient because strings are immutable, causing repeated memory reallocation. Which approach should the engineer implement to resolve the performance issue without changing the final output?

A.Replace `result += line.strip()` with `result = result + line.strip()`.
B.Use `io.StringIO` to write lines and then retrieve content with `.getvalue()`.
C.Use `str.join` called on the file object: `f.join('')`.
D.Use a list to collect stripped lines and then call `''.join(lines)` after the loop.
AnswerD

Store each stripped line as an element in a list during the loop; appending to a list is amortized O(1). After the loop, call `''.join(lines)` to allocate the final string exactly once and copy each part in a single pass, producing O(n) total work. This is the canonical idiom because it avoids repeated string reallocation and takes advantage of `str.join`'s optimized internal traversal of the sequence.

Why this answer

It avoids the O(n²) time complexity of repeated string concatenation by collecting stripped lines in a list and then joining them once with `''.join(lines)`. This leverages the efficient memory allocation of `str.join`, which precomputes the total size and allocates exactly once, solving the performance and memory issue without altering the final output.

Exam trap

Candidates often incorrectly believe that `result = result + line.strip()` is more efficient than `result += line.strip()`, but both have the same O(n^2) performance due to string immutability. The correct solution is to collect lines in a list and join them with `''.join()`.

How to eliminate wrong answers

Option A is wrong because `result = result + line.strip()` is semantically identical to `result += line.strip()` — both create a new string object and cause the same O(n²) reallocation overhead. Option B is wrong because `io.StringIO` is designed for in-memory text streams and would still require a final `.getvalue()` call, but it does not inherently solve the concatenation inefficiency; it adds unnecessary overhead for this simple accumulation task. Option C is wrong because `str.join` is a method on a string separator, not on a file object; `f.join('')` would raise an `AttributeError` since file objects have no `join` method.

45
MCQhard

A developer is building a large string by concatenating many substrings in a loop using '+'. What is the main performance issue?

A.Each concatenation creates a new string object, leading to quadratic time complexity
B.String concatenation is not allowed in loops
C.Strings are immutable, so concatenation is impossible
D.The '+' operator works only for characters, not strings
AnswerA

Strings in Python are immutable, and the `+` operator cannot modify an existing string; it must allocate a brand-new string object and copy the contents of both operands into it. When you concatenate in a loop, each iteration copies all previously accumulated characters plus the new piece, so total work grows quadratically (O(n^2)) as the string length increases. Using a list and `str.join()` avoids this repeated copying.

Why this answer

In Python, strings are immutable, so the '+' operator does not modify an existing string but creates a new string object each time it is used. In a loop, this results in O(n²) time complexity because each concatenation copies the entire accumulated string, making it highly inefficient for large or many substrings.

Exam trap

Python Institute often tests the misconception that string immutability means concatenation is impossible or illegal, when in fact the real issue is the hidden performance cost of repeated object creation in loops.

How to eliminate wrong answers

Option B is wrong because string concatenation using '+' is syntactically allowed inside loops in Python; the issue is performance, not legality. Option C is wrong because while strings are immutable, concatenation is still possible—it creates a new string rather than modifying the original. Option D is wrong because the '+' operator is overloaded for strings and works perfectly for concatenating two or more strings, not just characters.

46
MCQmedium

A programmer writes a function to check if a string is a palindrome (ignoring case and non-alphanumeric characters). Which implementation correctly achieves this?

A.def is_pal(s): s = s.lower(); return s == ''.join(reversed(s))
B.def is_pal(s): s = ''.join(c for c in s if c.isalnum()).lower(); return s == s[::-1]
C.def is_pal(s): return s == s[::-1]
D.def is_pal(s): s = s.lower(); return s == s[::-1]
AnswerB

This is the correct palindrome checker because it first strips out every non-alphanumeric character with a generator expression and ''.join(), then lowercases the cleaned string. Comparing this normalized form to its extended-slice reverse s[::-1] accounts for spaces, punctuation, and mixed case in one clean pass. This is the robust, idiomatic approach expected for a general-purpose palindrome test.

Why this answer

It first filters the string to keep only alphanumeric characters using `c.isalnum()`, converts the result to lowercase with `.lower()`, and then compares the string to its reverse using slicing `s[::-1]`. This correctly handles case insensitivity and ignores non-alphanumeric characters, which is the standard approach for palindrome checking in Python.

Exam trap

Python Institute often tests the requirement to ignore non-alphanumeric characters and case, and the trap here is that candidates may forget to filter the string before reversing, leading them to choose options A or D which only handle case but not punctuation.

How to eliminate wrong answers

Option A is wrong because it only converts the string to lowercase but does not remove non-alphanumeric characters, so strings like 'A man, a plan, a canal: Panama' would fail. Option C is wrong because it performs a direct comparison without any case normalization or character filtering, so it would incorrectly reject palindromes with mixed case or punctuation. Option D is wrong because it converts to lowercase but does not strip non-alphanumeric characters, leading to false negatives for strings containing spaces or punctuation.

47
Matchingmedium

Match each exception to its cause.

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

Concepts
Matches

Operation on incompatible type

Function receives argument with correct type but invalid value

Sequence subscript out of range

Mapping key not found

Attribute reference or assignment fails

Why these pairings

Correct matches: ValueError with inappropriate value, TypeError with wrong type, IndexError with out-of-range index, KeyError with missing key. Common confusions arise from swapping the definitions of ValueError and TypeError, or TypeError and KeyError.

48
MCQmedium

A developer is cleaning data from a CSV file. They have a string `record = "John,Doe,35,Engineer"` and want to replace all commas with semicolons. However, they also want to ensure that any leading or trailing whitespace in the entire string is removed before the replacement. Which expression produces the desired result?

A.record.strip(',').replace(',', ';')
B.record.replace(',', ';').strip()
C.record.strip().replace(',', ';')
D.record.replace(' ', '').replace(',', ';')
AnswerC

The expression first calls .strip() on the record, removing any leading and trailing whitespace. Then .replace(',', ';') replaces every comma with a semicolon. For the given string without extra whitespace, it yields 'John;Doe;35;Engineer'. If there were leading or trailing spaces, they would be removed before replacement. This meets both requirements in the correct order.

Why this answer

The correct approach is to strip leading and trailing whitespace first, then replace commas with semicolons. Using strip() before replace ensures that any surrounding whitespace is removed without affecting internal spaces. The other options either remove the wrong characters, remove all spaces, or perform the operations in a different order that might not align with the stated requirement, though in this specific case some yield the same output.

However, the requirement explicitly states 'before the replacement', making the strip-then-replace order the intended one.

Exam trap

The trap here is assuming that strip() removes commas or that replacing spaces globally is equivalent to stripping only the edges.

49
MCQmedium

A developer wants to remove all leading and trailing whitespace from a string, but preserve internal spaces. Which line of code accomplishes this?

A.s = s.lstrip()
B.s = s.strip().lstrip()
C.s = s.replace(' ', '')
D.s = s.strip()
AnswerD

The strip() method returns a copy of the string with all leading and trailing whitespace removed, using the standard set of whitespace characters including space, tab, and newline, while leaving internal spaces intact. This precisely satisfies the requirement, making it the correct and idiomatic way to trim a string in Python.

Why this answer

`s.strip()` removes all leading and trailing whitespace characters (spaces, tabs, newlines) from the string while preserving internal spaces. This is the exact requirement: eliminate whitespace at the boundaries only, leaving the internal content unchanged.

Exam trap

Python Institute often tests the distinction between `strip()`, `lstrip()`, and `rstrip()`, and the trap here is that candidates may confuse `strip()` with `replace(' ', '')` or think that `lstrip()` alone is sufficient, failing to recognize that `strip()` handles both ends in one call.

How to eliminate wrong answers

Option A is wrong because `s.lstrip()` only removes leading whitespace, leaving trailing whitespace intact. Option B is wrong because `s.strip().lstrip()` is redundant — `strip()` already removes both leading and trailing whitespace, so calling `lstrip()` afterward does nothing extra and is unnecessary. Option C is wrong because `s.replace(' ', '')` removes all spaces in the string, including internal ones, which destroys the internal spacing the developer wants to preserve.

50
Multi-Selecthard

Given s = 'Python', which THREE of the following expressions evaluate to True? (Choose three.)

Select 3 answers
A.'th' in s
B.s[0] == 'p'
C.s.isupper()
D.s.isalpha()
E.s.istitle()
AnswersA, D, E

The `in` operator performs a substring membership test, returning `True` when the literal characters `'th'` appear consecutively anywhere within `s`. In `'Python'`, the substring `'th'` is found at indices 2–3 (the third and fourth characters), so this expression evaluates to `True`. Note that substring matching is case-sensitive and does not require word boundaries.

Why this answer

The `in` operator checks for substring membership, and 'th' is indeed a contiguous substring within the string 'Python'. Python's `in` operator performs a linear scan of the string to determine if the substring exists, returning True if found.

Exam trap

The PCAP exam often tests the case-sensitivity of string methods and operators, trapping candidates who forget that `in`, indexing, and comparison methods like `isupper()` are case-sensitive and that `istitle()` requires the first letter of each word to be uppercase and all subsequent letters lowercase.

51
MCQeasy

A beginner programmer writes: name = "Alice"; print("Hello " + name). Which string method alternative is more efficient and recommended for Python 3?

A.print("Hello {}".format(name))
B.print("Hello %s" % name)
C.print(f"Hello {name}")
D.print("Hello " + name) is fine
AnswerC

An f-string (formatted string literal) is the recommended and most idiomatic way to embed `name` directly into the string. The expression inside `{}` is evaluated at runtime using the current scope, so `f"Hello {name}"` precisely reads as 'Hello, followed by the value of `name`'. This approach is concise, readable, and avoids the overhead of a separate method call or operator, making it both efficient and Pythonic. Since Python 3.6, f-strings are the preferred method for most string formatting tasks.

Why this answer

F-strings (formatted string literals) are the most efficient and readable string formatting method introduced in Python 3.6. They evaluate expressions at runtime and directly interpolate variables into the string, avoiding the overhead of method calls or the older %-formatting, making them both faster and more Pythonic.

Exam trap

Python Institute often tests the distinction between older formatting methods (%-formatting and str.format()) and the modern f-string syntax, trapping candidates who think any valid method is equally recommended, when in fact f-strings are the preferred and most efficient choice in Python 3.6+.

How to eliminate wrong answers

Option A is wrong because str.format() is less efficient than f-strings due to the overhead of a method call and additional parsing, and it is not the recommended approach for simple variable interpolation in modern Python 3. Option B is wrong because the %-formatting style is the legacy C-style printf approach, which is less readable, less flexible, and deprecated in favor of f-strings and str.format(). Option D is wrong because simple concatenation with + creates multiple intermediate string objects and is less efficient and less readable than f-strings, especially when combining multiple variables or expressions.

52
MCQmedium

A developer needs to parse a log file where each line contains a timestamp followed by a message. The timestamp format is 'YYYY-MM-DD HH:MM:SS'. Which string method is most appropriate to split the timestamp from the message?

A.str.rsplit()
B.str.splitlines()
C.str.partition()
D.str.split()
AnswerD

str.split() with no arguments splits on any run of whitespace, trimming leading and trailing spaces, and returns a list of non-empty substrings. For a log line like '2025-04-10 14:22:31 INFO message here', the timestamp (which contains no spaces) becomes the first element while the rest of the line is broken into subsequent elements, cleanly isolating the timestamp. It is the most direct method because it handles variable amounts of whitespace without requiring a separator to be specified.

Why this answer

Str.split(), is the most appropriate because it splits a string on whitespace by default. Although the timestamp 'YYYY-MM-DD HH:MM:SS' contains a space, using split() without arguments returns a list of all space-separated elements. Since the timestamp is always the first two elements (date and time), the developer can join them with a space to get the full timestamp.

Alternatively, split() can be used with a specified separator and maxsplit to achieve the desired split. This flexibility makes str.split() the best choice among the given options.

Exam trap

Python Institute often tests the distinction between str.split() and str.partition(), where candidates mistakenly choose str.partition() because they think it splits on the first space, but fail to realize that the timestamp itself contains a space, causing an incorrect split.

How to eliminate wrong answers

Option A is wrong because str.rsplit() splits from the right side of the string, which would incorrectly separate the last word of the message rather than the first space after the timestamp. Option B is wrong because str.splitlines() splits on line boundaries (newline characters), not on whitespace within a single line, so it cannot separate the timestamp from the message on the same line. Option C is wrong because str.partition() splits on the first occurrence of a specific separator string, but the timestamp contains spaces (between date and time), so using a space as the separator would split the timestamp itself, not separate it from the message.

53
MCQeasy

A developer uses the .index() method on a string to find the position of a substring. If the substring is not found, what exception is raised?

A.KeyError
B.IndexError
C.ValueError
D.TypeError
AnswerC

str.index() raises ValueError exactly when the substring argument cannot be found in the string. This is the documented, intentional behavior: ValueError signals that a value (the substring) is not present in the sequence. It matches the convention used by list.index() and tuple.index(), which also raise ValueError when the searched element is missing. Unlike .find(), which returns -1 as a sentinel, .index() chooses to raise so you must either catch the exception or check with 'in' first.

Why this answer

The `.index()` method on a string raises a `ValueError` when the specified substring is not found. This is because `ValueError` is the standard Python exception for cases where a function receives an argument with the correct type but an inappropriate value, such as a substring that does not exist in the target string.

Exam trap

The PCAP exam often tests the distinction between `.index()` (raises `ValueError`) and `.find()` (returns `-1`), trapping candidates who confuse the exception type with `IndexError` due to the word 'index' in the method name.

How to eliminate wrong answers

Option A is wrong because `KeyError` is raised when a dictionary key is not found, not when a substring is missing from a string. Option B is wrong because `IndexError` is raised when a sequence index is out of range (e.g., accessing a list element with an invalid index), not when a substring search fails. Option D is wrong because `TypeError` is raised when an operation is applied to an object of inappropriate type (e.g., passing an integer to `.index()` instead of a string), not when the substring is simply absent.

54
MCQmedium

A developer needs to combine a list of 10,000 strings into a single string. Which approach is most efficient in terms of memory and performance?

A.Use ''.join(string_list)
B.Use a loop with str += to concatenate each string
C.Use str.replace() to merge the strings
D.Use str.format() to build the string step by step
AnswerA

The str.join() method is optimized for this exact use case. It first iterates over string_list to calculate the total length, allocates a single backing buffer of exactly that size, and then copies each string into place without creating any intermediate objects. This results in O(n) time and minimal memory overhead, so it is the canonical and most efficient way to concatenate many strings.

Why this answer

The `''.join(string_list)` method is the most efficient because it pre-allocates memory for the final string by first calculating the total length of all strings in the list, then building the result in a single pass. This avoids the quadratic time complexity and repeated memory reallocations caused by string immutability in Python when using `+=` in a loop.

Exam trap

Python Institute often tests the misconception that `+=` is efficient for string concatenation because it works in other languages, but in Python, string immutability makes it a performance disaster for large lists.

How to eliminate wrong answers

Option B is wrong because using `str +=` in a loop creates a new string object for each concatenation, leading to O(n²) time complexity and excessive memory allocation due to Python's immutable strings. Option C is wrong because `str.replace()` is designed for substring replacement, not concatenation, and would require an initial string to operate on, making it unsuitable and inefficient for merging a list of strings. Option D is wrong because `str.format()` is intended for formatting placeholders, not for concatenating an arbitrary list of strings, and using it iteratively would still involve repeated string creation and poor performance.

55
MCQeasy

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

A.isalnum()
B.isspace()
C.isalpha()
D.isdigit()
AnswerC

isalpha() is correct because it returns True only when the string is non-empty and every character is classified as an alphabetic Unicode character, covering letters like 'A', 'é', and 'α' while rejecting digits, punctuation, and whitespace. This precisely matches the developer's requirement to check if a string contains only alphabetic characters. Note that it is not limited to ASCII, which is useful for internationalized input.

Why this answer

The `isalpha()` method returns `True` if all characters in the string are alphabetic (letters) and the string is non-empty. This directly matches the developer's requirement to check for only alphabetic characters.

Exam trap

The PCAP exam often tests the distinction between `isalpha()` and `isalnum()`, where candidates mistakenly choose `isalnum()` thinking it checks for letters only, but it actually includes digits as well.

How to eliminate wrong answers

Option A is wrong because `isalnum()` returns `True` if all characters are alphanumeric (letters or digits), so it would incorrectly accept strings containing digits. Option B is wrong because `isspace()` returns `True` only if all characters are whitespace, which is irrelevant for checking alphabetic content. Option D is wrong because `isdigit()` returns `True` only if all characters are digits, which is the opposite of the alphabetic check needed.

56
Multi-Selectmedium

Which TWO of the following methods return a boolean value?

Select 2 answers
A.str.upper()
B.str.isspace()
C.str.split()
D.str.join()
E.str.isalpha()
AnswersB, E

str.isspace() is a predicate method that returns True when the string is non-empty and every character in it is a whitespace character (space, tab, newline, carriage return, form feed, and similar Unicode spaces). If the string is empty or contains even one non-whitespace character, it returns False, making it useful for input validation and parsing. Thus, it directly answers the question's requirement of returning a boolean value.

Why this answer

The methods `str.isspace()` and `str.isalpha()` are both string methods that return a boolean value (`True` or `False`) based on whether the string meets specific character classification criteria. `isspace()` returns `True` if all characters in the string are whitespace, while `isalpha()` returns `True` if all characters are alphabetic.

Exam trap

Python Institute often tests the distinction between methods that return a new string or list versus those that return a boolean, leading candidates to mistakenly select methods like `str.upper()` or `str.split()` because they appear to perform a 'check' but actually return a transformed object.

57
MCQeasy

A data entry application reads a CSV file where each line contains fields separated by commas. However, some fields are enclosed in double quotes and contain commas inside, e.g., 'John,"Doe, Jr.",30'. The developer currently uses line.split(',') to parse each line, which incorrectly splits the quoted field. The developer wants a solution using only the Python standard library (no third-party packages). Which of the following is the best approach?

A.Use the csv module's reader: import csv; next(csv.reader([line]))
B.Use line.strip().split(',') and then manually merge fields that start with a quote
C.Iterate through each character, track whether inside quotes, and split on commas outside quotes
D.Write a regular expression that matches commas outside quotes
AnswerA

The csv module implements RFC 4180 quoting rules, so its reader correctly treats commas inside double-quoted fields as literal data rather than delimiters. Passing the single line in a list yields the parsed fields, and csv ships with the standard library.

Why this answer

The csv module's reader is specifically designed to handle CSV parsing according to RFC 4180, including quoted fields with embedded commas. By passing the line wrapped in a list to csv.reader, the developer gets a properly parsed list of fields without needing to manually handle quote escaping or comma splitting.

Exam trap

The PCAP exam often tests the candidate's knowledge of the standard library's csv module as the idiomatic and correct way to parse CSV data, expecting candidates to recognize that manual string splitting or regex approaches are fragile and not recommended for production code.

How to eliminate wrong answers

Option B is wrong because manually merging fields that start with a quote is error-prone and does not handle edge cases like escaped quotes ("") or fields that contain quotes but do not start with them. Option C is wrong because while character-by-character parsing can work, it is unnecessarily complex, error-prone, and reinvents the wheel when the csv module already provides a robust, tested implementation. Option D is wrong because writing a regular expression to match commas outside quotes is notoriously difficult to get right, especially with nested quotes or escaped quotes, and the csv module avoids this complexity entirely.

58
MCQmedium

Which method returns the lowest index where a specified substring is found, or -1 if not found?

A.find()
B.locate()
C.search()
D.index()
AnswerA

Python's find() returns the lowest index of the substring within the string, or -1 when absent, which is exactly the specified behaviour. index() raises ValueError instead of returning -1, and count() or search() do not return positional indices.

Why this answer

The `find()` method in Python returns the lowest index where the specified substring is found within the string, or -1 if the substring is not present. This behavior directly matches the question's requirement, making option A correct.

Exam trap

The PCAP exam often tests the distinction between `find()` and `index()`, where candidates mistakenly choose `index()` because it returns an index, forgetting that it raises an exception on failure instead of returning -1.

How to eliminate wrong answers

Option B is wrong because `locate()` is not a built-in string method in Python; it exists in other languages like JavaScript but not in Python's standard library. Option C is wrong because `search()` is a method from the `re` module for regex pattern matching, not a string method, and it returns a match object or None, not an index or -1. Option D is wrong because `index()` raises a `ValueError` exception when the substring is not found, rather than returning -1.

59
MCQhard

A programmer is writing a script to generate SQL queries safely. They need to escape single quotes in user-provided strings to prevent injection. Which approach is most robust?

A.s.replace("\\'", "'")
B.s.replace("'", "\\'")
C.s.strip("'")
D.s.replace("'", "''")
AnswerD

This doubles every single quote, which is the standard SQL way to include a literal quote inside a string: the DBMS sees '' as an escaped quote and does not treat the second quote as the end of the literal. By replacing all occurrences of ' with '', every potentially dangerous quote is neutralized, preventing break-out SQL injection when building queries from unsanitized input.

Why this answer

In SQL, single quotes are escaped by doubling them (''), not by using backslashes. This is the standard escape mechanism defined by the SQL standard (ISO/IEC 9075) and is supported by databases like PostgreSQL, SQLite, and Oracle. Using `s.replace("'", "''")` ensures that a single quote in user input becomes two single quotes in the SQL string, preventing injection while preserving the literal quote.

Exam trap

Python Institute often tests the misconception that backslash escaping is universal in SQL, leading candidates to choose Option B, but the PCAP exam expects knowledge of the standard SQL escape mechanism (doubling quotes) as the most robust method.

How to eliminate wrong answers

Option A is wrong because it replaces the backslash-quote sequence with a single quote, which does not escape anything and actually removes the escape character. Option B is wrong because it uses a backslash to escape the quote, which is not the standard SQL escape method and may not work in all databases (e.g., MySQL with NO_BACKSLASH_ESCAPES mode disables it). Option C is wrong because `strip("'")` only removes leading and trailing single quotes, leaving internal quotes unescaped and vulnerable to injection.

60
MCQmedium

Given s = 'Python', what is s[1:4]?

A.'pyt'
B.'yth'
C.'ytho'
D.'Pyt'
AnswerB

For s = 'Python', s[1:4] returns 'yth' because Python string indices are zero-based and slice end points are exclusive. The characters are P(0), y(1), t(2), h(3), o(4), n(5), so the slice takes positions 1, 2, and 3. Those positions spell 'y', 't', 'h' in order, giving exactly 'yth', which is the correct answer.

Why this answer

In Python, string slicing with `s[start:stop]` extracts characters from index `start` up to but not including index `stop`. Since indexing starts at 0, `s[1:4]` on 'Python' takes indices 1 ('y'), 2 ('t'), and 3 ('h'), resulting in 'yth'. Option B is correct because it exactly matches this slice.

Exam trap

Python Institute often tests the half-open interval behavior of slicing, where candidates mistakenly include the character at the stop index (e.g., choosing 'ytho' by including index 4) or confuse zero-based indexing with one-based indexing (e.g., choosing 'pyt' or 'Pyt' by starting at index 0).

How to eliminate wrong answers

Option A is wrong because 'pyt' would result from `s[0:3]` (lowercase 'p' at index 0, 'y' at 1, 't' at 2), not from `s[1:4]`. Option C is wrong because 'ytho' would require `s[1:5]` (including index 4 which is 'o'), exceeding the stop index of 4. Option D is wrong because 'Pyt' would result from `s[0:3]` (uppercase 'P' at index 0, 'y' at 1, 't' at 2), not from `s[1:4]` which starts at index 1.

61
MCQmedium

A developer writes a log message with variables: name = 'Alice' and age = 30. Which of the following uses an f-string correctly?

A.f(Name: {name}, Age: {age})
B.f'Name: {name}, Age: {age}'
C.'Name: %s, Age: %d' % (name, age)
D.f.'Name: {name}, Age: {age}'
AnswerB

This is a correctly formed f-string: the f prefix is directly attached to a single-quoted string literal, and each pair of curly braces contains an expression to be evaluated at runtime. Python inserts the values of the variables 'name' and 'age' into the string, converting them with their __format__ methods. The single quotes wrap the entire literal, making the syntax valid per PEP 498.

Why this answer

It uses the proper f-string syntax: the letter 'f' immediately followed by a string literal (single or double quotes) containing expressions in curly braces. In Python, f-strings (formatted string literals) evaluate expressions inside {} and insert them into the string at runtime, making them concise and readable.

Exam trap

The PCAP exam often tests the exact syntax of f-strings, specifically that the 'f' prefix must be immediately followed by a string literal (no space, no dot, no parentheses), and that the expressions inside curly braces are evaluated in the current scope.

How to eliminate wrong answers

Option A is wrong because the f-string prefix is missing the quotation marks — it uses parentheses instead of quotes, which is invalid syntax. Option C is wrong because it uses the old-style % formatting, not an f-string; while it works, it does not satisfy the requirement of using an f-string. Option D is wrong because it places a period between 'f' and the opening quote ('f.'), which is not valid Python syntax for an f-string.

62
MCQeasy

Consider the following code: name = "Alice" age = 30 print(f"{name} is {age} years old.") What is the output of the above code?

A.Alice is 30, years old.
B.Name is 30 years old.
C.Alice is 30 years old..
D.Alice is 30 years old.
AnswerD

In an f-string, expressions inside braces are evaluated and replaced with their string representation, so {name} becomes 'Alice' and {age} becomes '30'. The surrounding literal text ' is ' and ' years old.' is preserved verbatim, giving the exact concatenation 'Alice is 30 years old.'. This matches the expected output because the variable `name` holds the string 'Alice', and the integer `age` is 30.

Why this answer

Given the code:

name = "Alice"

age = 30

print(f"{name} is {age} years old.")

The f-string correctly interpolates the variables, producing 'Alice is 30 years old.' Option D is correct. Option A incorrectly includes an extra comma after 30. Option B uses the literal string 'Name' instead of the variable name. Option C adds an extra period at the end.

Exam trap

Python Institute often tests whether candidates notice subtle punctuation differences (like missing commas or extra periods) in f-string output, tricking those who focus only on the variable values and ignore exact string formatting.

How to eliminate wrong answers

Option A is wrong because it adds a comma after '30' and an extra space before 'years', which is not present in the f-string. Option B is wrong because it replaces the actual name with the literal string 'Name', showing a misunderstanding that f-string placeholders are evaluated, not left as variable names. Option C is wrong because it has two periods at the end (a double dot), while the f-string produces only one period.

63
Multi-Selectmedium

Which TWO of the following string methods return a boolean value (True or False)?

Select 2 answers
A.str.upper()
B.str.split()
C.str.startswith()
D.str.isdigit()
E.str.find()
AnswersC, D

str.startswith() is a predicate method: it evaluates the string against a condition and returns the boolean value True if the string begins with the given prefix, otherwise False. It also accepts optional start and end index arguments to scope the check, and can take a tuple of prefixes to test multiple alternatives at once. Because its entire purpose is to answer a Yes/No question about string content, it is one of the methods that truly returns a bool.

Why this answer

Both `str.startswith()` and `str.isdigit()` return a boolean value (`True` or `False`) because they are designed for conditional checks. `str.startswith()` checks if the string starts with a given prefix, while `str.isdigit()` checks if all characters in the string are digits. In contrast, `str.upper()` returns a new string, `str.split()` returns a list, and `str.find()` returns an integer index. Therefore, options C and D are the correct answers.

Exam trap

Python Institute often tests the distinction between methods that return a boolean versus those that return a new string or an integer, trapping candidates who confuse `str.find()` (returns index) with `str.startswith()` (returns boolean).

64
Multi-Selecteasy

Which TWO string methods raise an exception when the searched substring is not found?

Select 2 answers
A.rfind()
B.find()
C.rindex()
D.count()
E.index()
AnswersC, E

rindex() performs a right-to-left search but still returns the index of the match as measured from the left end of the original string. If the substring is not present, rindex() raises a ValueError, which is exactly the exception behavior that makes it a correct answer. It mirrors index() in its error semantics, differing only in the search direction.

Why this answer

(rindex()) is correct because the rindex() method, like index(), raises a ValueError exception when the searched substring is not found. This is in contrast to rfind() and find(), which return -1 instead of raising an exception.

Exam trap

Python Institute often tests the distinction between methods that return -1 (find, rfind) versus those that raise an exception (index, rindex), and the trap is that candidates confuse rfind() with rindex() because both perform a right-to-left search.

65
Multi-Selecthard

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

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

Immutability is a core property of Python strings: there is no in-place operation that modifies the characters or length of an existing str. Concatenation, for example with s1 + s2, does not extend s1; it allocates a new string whose content is the combined characters, leaving both operands untouched. This guarantee makes strings safe to use as dictionary keys and allows the interpreter to share or cache them.

Why this answer

Python strings are immutable, meaning once a string object is created, its content cannot be changed. Any operation that appears to modify a string, such as concatenation with the + operator, actually creates a brand-new string object in memory, leaving the original unchanged.

Exam trap

The PCAP exam often tests the immutability of strings by presenting options that imply strings behave like lists (e.g., item assignment or .append()), hoping candidates confuse string and list operations.

66
MCQeasy

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

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

The slice s[::-1] uses a negative step with default start and end, which makes Python traverse the string from the last character back to the first, producing the reversed string. Comparing this reversed result to the original string with == correctly determines whether s reads the same forward and backward, i.e., whether it is a palindrome.

Why this answer

The slicing syntax `s[::-1]` creates a reversed copy of the string `s`, and comparing it to `s` with `==` checks if the string reads the same forwards and backwards, which is the definition of a palindrome. For the string 'racecar', `s[::-1]` returns 'racecar', so the comparison is `True`.

Exam trap

The PCAP exam often tests the distinction between `reversed()` (which returns an iterator) and `[::-1]` (which returns a reversed sequence), and the fact that strings are immutable and lack a `.reverse()` method, leading candidates to confuse list methods with string operations.

How to eliminate wrong answers

Option A is wrong because `reversed(s)` returns a reverse iterator object, not a string, so comparing it to `s` with `==` will always be `False` (they are different types). Option B is wrong because `s[::1]` returns the string unchanged (step 1 from start to end), so it compares the string to itself and always returns `True`, not checking for palindrome. Option D is wrong because strings in Python have no `.reverse()` method; that method exists only for lists, so this would raise an `AttributeError`.

67
MCQeasy

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

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

s.isalnum() exactly implements the required test: it returns True only for non-empty strings where every character is a Unicode letter or digit, accepting both 'hello123' and accented letters like 'café'. It also recognizes Unicode digits such as '١' while correctly rejecting spaces, punctuation, and symbol characters like '#' or '!'. Because the condition is precisely that the string contains only alphanumeric characters, this is the correct method and also implies that isalpha() or isdigit() would be too restrictive individually.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

68
MCQhard

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

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

This expression builds a list containing only the digit characters from the input and then compares its length to 10. It therefore passes any string that contains exactly ten digits, regardless of additional letters, spaces, hyphens, or punctuation, because non-digits are simply filtered out before counting. This precisely matches the requirement to validate that user input contains ten digits without insisting on a specific format.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

69
MCQhard

What is the likely outcome of running the following code? ```python with open("C:\Users\path\file.txt", "r") as f: print(f.read()) ```

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

A normal string literal is parsed by the Python compiler before any code executes, and every backslash must form a legal escape sequence. `\U` is the escape prefix for a 32-bit Unicode code point and must be followed by exactly eight hexadecimal digits; here it is truncated, so the tokenizer raises `SyntaxError: (unicode error) ... truncated \UXXXXXXXX escape` at compile time. Consequently, no program output or file operation ever occurs.

Why this answer

The code likely contains backslash sequences (e.g., `\U`, `\p`, or other non-standard escapes) that are not valid escape sequences in Python. Starting with Python 3.12, such invalid sequences raise a `SyntaxError` at compile time, preventing the program from running. In earlier versions, a `DeprecationWarning` is issued, but the code may run.

The error is not about file operations or path resolution; it's a compile-time syntax error. To avoid this, use raw strings (`r"..."`) or double backslashes (`\\`).

Exam trap

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

How to eliminate wrong answers

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

70
MCQmedium

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

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

The \b word boundary anchors ensure that 'excellent' is matched only when it stands as its own word, not as a substring of a larger token, while the re.IGNORECASE flag makes the match case-insensitive. Because re.search scans the entire string but the boundary restricts the match position, this option correctly finds 'Excellent', 'excellent.', and 'excellent' while rejecting 'unexcellent'. This is the only approach that combines whole-word semantics with case-insensitive matching in a single call.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

71
Multi-Selecthard

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

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

The join() method is invoked on the separator string, and it takes an iterable of strings as its argument. For example, ','.join(['a', 'b']) returns 'a,b' by inserting the separator between each pair of elements. The separator string is not modified; it is reused as the delimiter, and every element in the iterable must be a string or a TypeError will be raised.

Why this answer

The join() method is called on the separator string, not on the iterable. For example, ','.join(['a', 'b']) returns 'a,b'. The separator is the string that will be placed between each element of the iterable passed as an argument.

This is a common point of confusion because many learners mistakenly think join() is called on the list.

Exam trap

PCAP often tests the immutability of strings by presenting a statement that suggests strings can be changed in place, catching candidates who confuse strings with mutable sequence types like lists.

72
MCQeasy

What is the output of the code in the exhibit?

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

The f-string's placeholders are evaluated at runtime: {name} is replaced by the value of the variable name, which is 'Alice', and {age} is replaced by the value of age, which is 30. The resulting concatenated string matches exactly this output, making it the correct answer.

Why this answer

The code uses an f-string which substitutes the values of the variables `name` and `age` into the string. Evaluating the expression results in 'Alice is 30 years old.', matching option B. Option A shows the literal braces, option C displays the variable names instead of their values, and option D reverses the order of the variables.

Exam trap

The trap here is that candidates may confuse f-strings with regular strings and think the literal text {name} and {age} is printed, or they may misorder the variables in the output, leading them to choose option A or D instead of recognizing the correct substitution.

How to eliminate wrong answers

Option A is wrong because it shows the raw f-string template with {name} and {age} unsubstituted, which would only appear if the string were printed without the 'f' prefix or if the variables were not defined. Option C is wrong because it is identical to option B, but the question expects the exact output including the period at the end; however, both B and C are the same string, so the correct answer is B as marked. Option D is wrong because it reverses the order of the variables, placing age before name, which does not match the f-string's defined order in the code.

73
MCQeasy

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

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

Passing a space as the argument restricts strip() to that character set only, so leading and trailing spaces are removed while tabs, newlines and other whitespace remain intact. The bare strip() call would strip all whitespace types, violating the stated requirement.

Why this answer

The strip() method in Python, when called with no arguments, removes all leading and trailing whitespace characters, including spaces, tabs, and newlines. By passing a space character as the argument, strip(' '), the method is instructed to remove only that specific character (space) from the ends of the string, leaving tabs and newlines intact. This directly meets the requirement to remove only leading and trailing spaces.

Exam trap

The trap here is that candidates often assume strip() without arguments only removes spaces, but the PCAP exam tests the nuance that strip() by default removes all whitespace characters, and that passing a specific character as an argument restricts the removal to that character only.

How to eliminate wrong answers

Option A is wrong because replace(' ', '') removes all spaces everywhere in the string, not just leading and trailing ones, which would alter the internal content of the string. Option B is wrong because lstrip() and rstrip() with no arguments remove all leading and trailing whitespace (including tabs and newlines), which is exactly what the developer wants to avoid. Option C is wrong because split() and join() would split the string on whitespace and rejoin it, which removes all whitespace (including internal spaces) and does not specifically target only leading and trailing spaces.

74
MCQhard

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

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

When t = s executes, both variables reference the same immutable string object containing 'Python'. Later, s = s + '3.0' creates a new string object and rebinds only s; t remains bound to the original object. Therefore printing t outputs 'Python'.

Why this answer

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

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

Exam trap

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

How to eliminate wrong answers

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

Page 1 of 3 · 151 questions totalNext →

Ready to test yourself?

Try a timed practice session using only Strings questions.