CCNA Strings Questions

30 of 181 questions · Page 3/3 · Strings · Answers revealed

151
Multi-Selecteasy

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

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

Correct: returns a new string with replacements.

Why this answer

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

Exam trap

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

152
MCQmedium

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

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

Correct: The first 'l' is at index 2.

Why this answer

The find() method returns the lowest index where the substring 'l' is found. In 'Hello', the first 'l' is at index 2 (0-based).

153
Multi-Selecthard

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

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

Full slice returns the entire string.

Why this answer

Slicing with [0:6], [:], and [0:6:1] all return the entire string 'Python'. [:-1] returns 'Pytho', and [::2] returns 'Pto'.

154
Multi-Selecteasy

Which TWO of the following are immutable in Python?

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

Tuples are immutable.

Why this answer

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

Exam trap

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

155
MCQmedium

A developer wrote a script that processes user input. The script expects a string containing a list of comma-separated values. The user enters "apple, banana, cherry, date". The script uses split() to separate the items. Which code correctly extracts the second item without leading/trailing spaces?

A.items = data.split(); second = items[1]
B.items = data.split(", "); second = items[1]
C.items = data.split(","); second = items[1].strip()
D.items = data.split(","); second = items[2].strip()
AnswerB

Correctly splits on comma-space, directly obtaining the second item without extra spaces.

Why this answer

Option B correctly splits on ', ' which matches the input format, returning the second item without extra spaces. Option A also works but is less direct. Option C splits on whitespace, including commas in items.

Option D gets the third item.

156
Multi-Selecthard

Which TWO of the following expressions yield the substring 'Py' from the string s = 'Python'?

Select 2 answers
A.s[0:-4]
B.s[0:2:2]
C.s[-6:-3]
D.s[0:2]
E.s[0:1]
AnswersA, D

Correct: from 0 to -4 (exclusive), which is indices 0 and 1.

Why this answer

Option A is correct because s[0:-4] uses negative indexing to slice from index 0 up to (but not including) index -4, which corresponds to the character 'o' (the fifth character from the end). Since 'Python' has length 6, index -4 is the character at position 2 (0-based), so the slice returns characters at indices 0 and 1, which are 'P' and 'y', yielding 'Py'.

Exam trap

Python Institute often tests the interaction between negative indexing and step values, trapping candidates who forget that a step of 2 skips characters or that negative indices count from the end, leading them to select options that return only one character or an incorrect substring.

157
Multi-Selectmedium

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

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

Returns a new string with all lowercase characters.

Why this answer

Option B (str.lower()) is correct because, despite Python strings being immutable, the question asks which methods 'modify the string in place' as a trick. In reality, none of these methods modify the string in place; they all return a new string. However, the PCAP exam sometimes tests whether you know that str.lower() and str.upper() are the only methods among the options that return a new string with the entire string transformed, while the others are often mistakenly thought to modify the original.

The key is that the question's premise is false, and the 'correct' answers are the ones that are most commonly associated with in-place modification in other languages, but in Python they do not.

Exam trap

Python Institute often tests the misconception that string methods like str.replace() or str.strip() modify the string in place, when in fact all string methods return new strings due to immutability, and the question's premise is deliberately misleading to catch candidates who do not understand that no string method modifies in place.

158
MCQmedium

A developer gets the following error while running a Python script: 'TypeError: not all arguments converted during string formatting'. The relevant code is: print('Progress: %d%%' % (percent)). The variable 'percent' is an integer. What is the most likely cause and fix?

A.There is a mismatch between the number of format specifiers and the number of arguments; add another argument.
B.Convert the integer to a string using str(percent) before formatting.
C.The percent sign must be escaped as '%%' to be treated as a literal.
D.Switch from %-formatting to an f-string: f'Progress: {percent}%'
AnswerC

In %-formatting, a literal percent sign is represented by '%%'.

Why this answer

Option B is correct because the percent sign (%) inside the string is interpreted as a format specifier, not a literal. To insert a literal percent sign, it must be escaped as '%%'. Option A is wrong because the number of arguments matches (one format specifier %d).

Option C is wrong because f-strings, while modern, are not required to fix this particular error. Option D is wrong because int() conversion is unnecessary.

159
Multi-Selecthard

Which THREE are valid escape sequences in Python strings?

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

Newline escape sequence.

Why this answer

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

Exam trap

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

160
Multi-Selectmedium

Which TWO of the following are valid string methods in Python? (Choose two.)

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

Valid method, capitalizes first character.

Why this answer

A is correct because `.capitalize()` is a built-in string method in Python that returns a copy of the string with its first character capitalized and the rest lowercased. It is part of the standard string methods documented in Python's official library reference.

Exam trap

Python Institute often tests the exact naming of string methods, and the trap here is that candidates may confuse `.uppercase()` or `.titlecase()` with the real methods `.upper()` and `.title()`, or mistakenly think `.swapcase()` is invalid when it is actually a valid method but not one of the two required correct answers.

161
MCQeasy

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

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

Correct slice from index 1 to 3 exclusive gives 'e' (index1) and 'l' (index2).

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

162
MCQhard

Which of the following expressions raises a ValueError?

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

Substring not found; raises ValueError.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

163
Multi-Selecteasy

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

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

Triple quotes allow the string to span multiple lines, even with escape sequences.

Why this answer

Triple-quoted strings (options B and E) allow literal newlines in the source code. Options A and D use escape sequences but are single-line in source. Option C is concatenation on one line.

164
Matchingmedium

Match each variable scope to its description.

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

Concepts
Matches

Inside a function

At module level

In outer function (nested)

Predefined names in Python

Variable from enclosing scope (not global)

Why these pairings

Python variable scopes (LEGB rule).

165
Multi-Selecteasy

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

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

Strings support slicing to extract substrings.

Why this answer

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

Exam trap

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

166
MCQeasy

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

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

endswith() returns True if the string ends with the given suffix.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

167
MCQhard

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

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

Width 10, precision 2, fixed-point formatting.

Why this answer

Option C is correct because the format specifier '10.2f' means width 10, precision 2, fixed-point. Option A is wrong because '.2f' has no width. Option B is wrong because '10.2e' uses scientific notation.

Option D is wrong because '10.2g' uses general format which may not always show 2 decimal places.

168
MCQeasy

A junior developer is building a script to convert user-provided headlines into URL slugs. The slug should contain only lowercase alphanumeric characters and single hyphens between words, with no leading or trailing hyphens. For example, 'Hello World! How are you?' should become 'hello-world-how-are-you'. The current code is: slug = input_string.lower().replace(' ', '-').replace('!', '').replace('?', ''). However, this produces multiple hyphens when there are multiple spaces, and trailing hyphens if the string ends with punctuation. The developer needs to modify the code to handle these issues reliably. Which of the following approaches is the most robust and efficient?

A.Use string.replace multiple times to replace punctuation and then replace multiple spaces with a single hyphen
B.Use re.sub(r'[^a-z0-9]+', '-', input_string.lower()).strip('-')
C.words = [w.strip('!?.,') for w in input_string.lower().split()]; slug = '-'.join(filter(None, words))
D.Iterate over each character, build a list of allowed characters, and join with hyphens
AnswerC

Cleanly splits on whitespace, strips punctuation, filters empties, and joins with hyphen.

Why this answer

Option B splits the string into words (using split() which handles multiple spaces), strips punctuation from each word, filters out empty strings, and joins with a single hyphen. This ensures no multiple hyphens or leading/trailing hyphens. Option A uses regex but is more complex and may still have edge cases.

Option C uses replace with regex but similar issues. Option D is a manual loop that is less efficient and error-prone.

169
MCQhard

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

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

Correct: s[::-1] creates a new reversed string without modifying the original.

Why this answer

Strings are immutable in Python, so slicing returns a new string. The step -1 reverses the sequence. The function works for any string, including empty strings.

170
MCQmedium

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

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

Strings are immutable, so item assignment is not allowed.

Why this answer

Option A is correct because strings are immutable; assigning to an index raises TypeError. Option B is wrong because it does not assign a new string; assignment to index fails. Option C is wrong because it raises an error, it does not succeed.

Option D is wrong because the error is TypeError, not IndexError.

171
MCQeasy

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

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

Splits by '.' and returns the last element, which is the extension.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

172
MCQhard

A log analysis script needs to extract all IP addresses from a string. The IPs are in dotted-decimal format. Which regex pattern will correctly extract them?

A.r'[0-9]+\. [0-9]+\.[0-9]+\.[0-9]+'
B.r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'
C.r'(?:[0-9]{1,3}\.){3}[0-9]{1,3}'
D.r'\d+\.\d+\.\d+\.\d+'
AnswerC

Matches three groups of 1-3 digits followed by dot, then one more group. Does not validate range beyond 999, but typical for IP extraction.

Why this answer

Option C is correct because it uses a non-capturing group `(?:...)` to repeat the pattern `[0-9]{1,3}\.` exactly three times, followed by a final octet `[0-9]{1,3}`. This matches the dotted-decimal structure of an IPv4 address (four octets, each 1–3 digits, separated by dots) without introducing extra spaces or overly permissive digit counts, and it avoids capturing unnecessary groups.

Exam trap

Python Institute often tests the distinction between capturing and non-capturing groups, and the trap here is that candidates see option B (which also works) and assume it is correct, but the exam expects the more efficient non-capturing group syntax (C) as the proper regex for extraction without unnecessary overhead.

How to eliminate wrong answers

Option A is wrong because it includes a space after the first dot (`\. [0-9]+`), which would not match a properly formatted IP address (e.g., it would require '192. 168.1.1' instead of '192.168.1.1'). Option B is wrong because it uses `\d{1,3}` which matches 1 to 3 digits, but this pattern is identical in function to C; however, B is not the correct answer because the question specifically expects the non-capturing group syntax (C) as the correct regex, and B is technically valid but not the intended answer (the trap is that B also works but C is more efficient and matches the PCAP emphasis on non-capturing groups). Option D is wrong because `\d+` matches one or more digits with no upper limit, allowing octets like '9999' or '12345', which are invalid for IPv4 (each octet must be 0–255, and while regex alone cannot enforce the numeric range, `\d+` is too permissive and would match malformed addresses).

173
Multi-Selectmedium

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

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

Valid: tab.

Why this answer

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

Exam trap

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

174
Multi-Selecthard

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

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

Efficiently builds the string in one pass.

Why this answer

Using join() on a list of strings is efficient because it allocates the final string once. Using StringIO from the io module builds a mutable buffer, also efficient. The += and + operators create a new string object for each concatenation, leading to O(n^2) time. % formatting also creates a new string each iteration.

175
MCQhard

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

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

String literals are often interned, so a and b reference the same object.

Why this answer

Due to string interning in CPython, string literals may be the same object. Thus a is b returns True. Option B is incorrect because interning often caches small strings.

176
Drag & Dropmedium

Drag and drop the steps to install a third-party package using pip in Python into the correct order.

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

Steps
Order

Why this order

Installing a package with pip involves opening terminal, checking pip, using install command, optionally specifying version, and verifying.

177
MCQmedium

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

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

Correct: the string object itself is immutable, but the variable can point to a new string.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

178
Multi-Selectmedium

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

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

strip() removes whitespace from both ends, effectively removing leading whitespace.

Why this answer

Both strip() (removes both ends) and lstrip() (removes only leading) remove leading whitespace. rstrip() removes trailing. split() and chomp() are not correct.

179
MCQeasy

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

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

The slice [::-1] creates a reversed copy of the string.

Why this answer

Option B is correct because Python's slice notation `[::-1]` creates a reversed copy of the string by stepping through the sequence from end to start with a step of -1. Strings are immutable, so this returns a new string object with the characters in reverse order, exactly converting 'stressed' to 'desserts'.

Exam trap

Python Institute often tests the distinction between methods that modify in-place (like `list.reverse()`) and those that return a new object (like string slicing), trapping candidates who confuse list methods with string operations.

How to eliminate wrong answers

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

180
Multi-Selecteasy

Which TWO of the following are valid ways to use string formatting in Python? (Choose two.)

Select 2 answers
A."Hello {0}".format("World")
B."Hello $s" % "World"
C.f"Hello {world}"
D."Hello %s" % "World"
E."Hello {name}".format("World")
AnswersA, D

Valid .format() method.

Why this answer

Old-style formatting with % and the .format() method are both valid and widely used. Option C uses $s which is invalid, D would raise KeyError, and E assumes a variable that may not be defined.

← PreviousPage 3 of 3 · 181 questions total

Ready to test yourself?

Try a timed practice session using only Strings questions.