PCAP · domain
Strings
The Strings domain covers Python's immutable str type: indexing, slicing, concatenation, and the methods that inspect and transform text. Questions ask you to predict exact output from slicing expressions, choose the right method for a task, and apply format specifiers. Expect code-reading items where one character of difference in a slice bound or format spec changes the result.
Focused practice
Practice Strings questions
Scored sessions drawing only from this domain — pick a length below.
Start 20-question practice test →What this domain covers
What to know about Strings
You must read a string expression and state its exact value, pick the correct method for a described task, and build a format specifier that matches a required width, alignment, and precision. The single most important thing: remember slice stop indices are exclusive and format precision follows the dot.
Slicing with start, stop, and step, including negative indices and omitted bounds
String methods such as isalnum, isalpha, isdigit, split, join, strip, and replace
The format() method and f-strings with width, alignment, precision, and type specifiers
Immutability of str and how operations like concatenation or replace return new strings
Watch out for
Common Strings exam traps
- ▸Assuming the stop index in a slice is included; it is excluded, so s[0:6] returns six characters, not seven.
- ▸Confusing isalnum with isalpha or isdigit; isalnum accepts letters and digits but rejects spaces and punctuation.
- ▸Misreading format specifiers like {:10.2f}; the width comes before the dot and precision after, and alignment defaults to right for numbers.
Question index
All Strings questions (151)
Click any question to see the full explanation, or start a practice session above.
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?
Medium2Refer to the exhibit. What happens when the code is executed?
Medium3A 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?
Hard4Which THREE of the following are immutable types in Python?
Medium5What happens when you execute the following code? s = 'hello'; s[0] = 'H'
Hard6A 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?
Hard7Drag and drop the steps to handle an exception in Python using try-except-finally into the correct order.
Medium8You 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?
Hard9What is the cause of the error?
Medium10Consider the following code: print(type('apple,banana,cherry'.split(','))) What type of value is printed?
Easy11A 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?
Medium12You 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?
Hard13What is the result of 'PyThon'.lower()?
Easy14A 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?
Hard15What is the result of the expression 'Hello' * 3?
Easy16Which THREE of the following string methods return a boolean value (True or False)? (Choose exactly 3 correct answers.)
Medium17Which of the following is the BEST practice for building a large string by concatenating many smaller strings in Python?
Easy18Refer to the exhibit. Which of the following fixes the error?
Medium19Which TWO statements are true regarding strings in Python?
Medium20A 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?
Medium21A developer writes code to display a floating-point number with exactly two decimal places. Which f-string expression is correct for value = 3.14159?
Medium22A 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`?
Medium23A 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?
Easy24A 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?
Easy25You 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?
Hard26Which TWO string methods are used to determine if a string begins or ends with a specified prefix or suffix? (Choose two.)
Easy27A 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?
Hard28A 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?
Hard29A developer wants to check if a string 'example.txt' ends with '.txt'. Which expression returns True?
Easy30A 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'?
Hard31A 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?
Medium32A 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?
Medium33What does the expression 'hello world'.title() return?
Medium34Match each string method to its purpose.
Medium35What is the value of matches?
Hard36Which TWO of the following string methods return a new string with all characters converted to lowercase? (Select exactly two.)
Medium37Which THREE of the following are true about Python strings?
Medium38What is the result of 'abcdef'[::-2]?
Hard39A 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?
Medium40A 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?
Hard41A developer wants to convert a string 'Python' to all uppercase letters. Which string method should be used?
Easy42A 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?
Easy43What is the output of `print('-'.join(['a', 'b', 'c']))`?
Easy44A 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?
Hard45A developer is building a large string by concatenating many substrings in a loop using '+'. What is the main performance issue?
Hard46A programmer writes a function to check if a string is a palindrome (ignoring case and non-alphanumeric characters). Which implementation correctly achieves this?
Medium47Match each exception to its cause.
Medium48A 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?
Medium49A developer wants to remove all leading and trailing whitespace from a string, but preserve internal spaces. Which line of code accomplishes this?
Medium50Given s = 'Python', which THREE of the following expressions evaluate to True? (Choose three.)
Hard51A beginner programmer writes: name = "Alice"; print("Hello " + name). Which string method alternative is more efficient and recommended for Python 3?
Easy52A 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?
Medium53A 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?
Easy54A 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?
Medium55A developer wants to check if a string contains only alphabetic characters. Which string method should be used?
Easy56Which TWO of the following methods return a boolean value?
Medium57A 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?
Easy58Which method returns the lowest index where a specified substring is found, or -1 if not found?
Medium59A 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?
Hard60Given s = 'Python', what is s[1:4]?
Medium61A developer writes a log message with variables: name = 'Alice' and age = 30. Which of the following uses an f-string correctly?
Medium62Consider the following code: name = "Alice" age = 30 print(f"{name} is {age} years old.") What is the output of the above code?
Easy63Which TWO of the following string methods return a boolean value (True or False)?
Medium64Which TWO string methods raise an exception when the searched substring is not found?
Easy65Which TWO statements about Python strings are correct? (Choose exactly 2 correct answers.)
Hard66A developer wants to check if a string 'racecar' is a palindrome by comparing it to its reverse. Which code completes the task correctly?
Easy67A developer needs to check if a string contains only alphanumeric characters. Which string method should be used?
Easy68A 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?
Hard69What is the likely outcome of running the following code? ```python with open("C:\Users\path\file.txt", "r") as f: print(f.read()) ```
Hard70You 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?
Medium71Which three of the following statements about Python strings are true? (Choose three.)
Hard72What is the output of the code in the exhibit?
Easy73A 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?
Easy74Given the code: s = 'Python'; t = s; s = s + '3.0'. What is the value of t after these lines execute?
Hard75What is the output?
Easy76A developer needs to count the number of occurrences of the substring 'is' in the string 'This is a test. Is this a test?'. Which code correctly performs the count?
Medium77Which THREE are valid ways to create a multiline string in Python?
Medium78Refer to the exhibit. What is the output?
Hard79Which of the following expressions returns True if the string s contains only hexadecimal digits (0-9, a-f, A-F)?
Hard80A developer is formatting a log message and wants to ensure that a string variable `name` is centered within a field of width 20, padded with asterisks (`*`) on both sides. For example, if `name = "Alice"`, the result should be `*******Alice********` (7 asterisks on the left, 8 on the right). Which method call achieves this?
Easy81Given s = 'a1b2c3', which TWO of the following expressions return the string '123'?
Hard82Which TWO of the following can be used to remove leading whitespace (spaces, tabs, newlines) from a string? (Choose exactly 2 correct answers.)
Medium83A developer wants to remove leading and trailing whitespace from a string. Which method should be used?
Medium84Which of the following is the correct way to format a string to include a variable value with two decimal places in Python?
Medium85A developer needs to check if a filename starts with the prefix 'report_'. Which string method should be used?
Easy86Which TWO of the following string methods return a boolean value?
Easy87You are a developer for an e-commerce platform. The system receives product descriptions from suppliers in various formats. One supplier sends descriptions with inconsistent capitalization, extra whitespace, and occasional leading/trailing punctuation. Your task is to write a function that normalizes these descriptions: convert to lowercase, remove leading/trailing whitespace and punctuation (.,!?;:), and replace multiple spaces with a single space. The function should return the cleaned string. Which implementation correctly performs all these steps?
Medium88A programmer has a string 'apple,banana,orange' and wants to get a list ['apple', 'banana', 'orange']. Which method should be used?
Easy89A programmer has a string s = 'Python programming is fun'. They want to extract the word 'programming'. Which slicing expression achieves this?
Medium90A logging module receives a message that may contain sensitive data. To comply with data privacy, all digits in the message should be replaced with 'X' before logging. Which approach correctly achieves this?
Medium91What is the result of the expression 'aBc'.lower()?
Easy92A programmer needs to replace every occurrence of 'cat' with 'dog' in a string s, but only if 'cat' is not preceded by 'big'. Which regex substitution would achieve this?
Medium93What is the output of 'hello'.count('l')?
Easy94Which of the following demonstrates that strings are immutable?
Medium95What is the result of 'Python'.find('th')?
Medium96Drag and drop the steps to debug a Python script using pdb into the correct order.
Medium97A user entered a string ' Hello, World! '. Which expression returns 'Hello, World!'?
Easy98Which THREE methods return a boolean value?
Hard99A developer is working on a logging system where dynamic values are inserted into a template string. The template is 'User %s logged in at %s'. The developer has the username and timestamp as separate variables. Which approach is most Pythonic (PEP 498) and recommended for new code?
Medium100When processing a large text file, a developer notices that using str.replace() in a loop is slow. Which alternative is most efficient for multiple replacements?
Medium101A developer writes: s = 'abc'; s[0] = 'x'. What happens?
Hard102Which THREE of the following are valid ways to create a string in Python?
Hard103Which of the following expressions returns the string 'Hello' repeated three times?
Easy104Which expression returns the last character of string s?
Easy105Which THREE of the following escape sequences are valid in a Python string and represent a single character? (Select exactly three.)
Hard106Which string method would you use to check if a string starts with a specified prefix?
Easy107What is the result of the expression '123'.zfill(5)?
Hard108A developer is building an IoT application that reads temperature data from a sensor over a TCP socket. The sensor sends data as a stream of bytes encoded in UTF-8, with each reading terminated by a newline character. The developer uses the following code to receive data: ```python import socket s = socket.socket() s.connect(('sensor.local', 5000)) data = s.recv(1024) ``` The variable `data` is a bytes object. The developer needs to convert it to a string to parse the temperature value. Which of the following lines of code should the developer use to correctly obtain the string representation of the received data, assuming the data is valid UTF-8 and may contain non-ASCII characters?
Easy109Refer to the exhibit. What is the output of the code?
Medium110What will the above code output?
Medium111Given the code above, what is printed? Note: each backslash is a single character.
Hard112A developer is validating user input in a Python application. The string variable `input_str` is assigned the value `'Hello World'`. Which TWO of the following conditions evaluate to `True`? (Choose two.)
Medium113Consider the following code snippet: s = 'abcdefgh'; result = s[7:3:-2]; print(result). What is the output?
Hard114A web application receives a byte string b'\xc3\xa9' which represents the character 'é' in UTF-8. The developer wants to convert it to a Python string. Which operation should be used?
Hard115Which THREE of the following string methods can be used to split a string into a list of substrings? (Choose three.)
Medium116A developer writes: print('{:,}'.format(1234567)). What is the output?
Hard117Which TWO of the following are valid string methods in Python?
Easy118A developer needs to extract the file extension from a filename like 'document.pdf'. Which expression returns 'pdf'?
Hard119What is the result of the expression '12345'[:10]?
Easy120Given the string 'Python', what is the result of 'Python'[::-1]?
Hard121Which TWO of the following expressions evaluate to `True`? (Select exactly two.)
Easy122Which string method can be used to check if a string contains only digits?
Easy123Consider the following code: result = ' '.join(['a', 'b', 'c']) print(repr(result)) What is the output?
Hard124Refer to the exhibit. A Python script uses re.split with a regex pattern. What is the output?
Hard125A data scientist needs to count the occurrences of a substring in a long DNA sequence (e.g., 1 million bases). However, the count must include overlapping occurrences. For example, in 'AAAA', the substring 'AA' appears three times overlapping. The built-in count() method does not count overlapping matches. The scientist needs a function to count overlapping substrings efficiently without using third-party libraries. Which of the following approaches is the most efficient for this task?
Hard126Consider the following code: print('"age": 30,')
Hard127Which TWO of the following string methods return a new string without modifying the original?
Easy128What is the output of the following code? s = 'Hello'; print(s.find('l'))
Medium129Which THREE of the following expressions return the string "Python"? (Choose three.)
Hard130Which TWO of the following are immutable in Python?
Easy131Which TWO of the following string methods modify the string in place? (Note: Python strings are immutable.)
Medium132Which THREE are valid escape sequences in Python strings?
Hard133Which THREE of the following are valid string methods in Python? (Choose three.)
Medium134What is the result of the expression 'Hello'[1:3]?
Easy135Which of the following expressions raises a ValueError?
Hard136Which two of the following are valid ways to create a multiline string in Python source code? (Choose two.)
Easy137Match each variable scope to its description.
Medium138A developer is building a configuration parser. They have a string `line = " key = value "` and need to remove the leading and trailing spaces, then split the line at the equals sign into a list of exactly two elements: the key and the value, with any spaces around the equals sign removed. Which expression achieves this?
Medium139Which TWO of the following operations can be performed on a string?
Easy140A developer wants to check if a string ends with a specific suffix. Which method should be used?
Easy141A 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?
Hard142A 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?
Hard143A developer tries to modify a string: s = 'hello'; s[0] = 'H'. What happens when this code runs?
Medium144A developer needs to extract the file extension from a string like 'report.pdf'. Which string method is most appropriate?
Easy145Which THREE of the following are valid escape sequences in Python strings?
Medium146In a performance-critical application, you need to concatenate many strings in a loop. Which TWO approaches are most efficient?
Hard147Under CPython, what is the result of the following code? a = 'hello'; b = 'hello'; print(a is b)
Hard148Which of the following best describes the immutability of strings in Python?
Medium149Which two methods can be used to remove leading whitespace from a string? (Choose two.)
Medium150A programmer writes a function that expects a string and returns it reversed. Which code snippet correctly reverses the string 'stressed' to 'desserts'?
Easy151Which TWO of the following are valid ways to use string formatting in Python? (Choose two.)
EasyOther domains
All PCAP exam domains
Frequently asked questions
- What does the Strings domain cover on the PCAP exam?
- You must read a string expression and state its exact value, pick the correct method for a described task, and build a format specifier that matches a required width, alignment, and precision. The single most important thing: remember slice stop indices are exclusive and format precision follows the dot.
- How many questions are in this domain?
- This page lists all 151 Strings questions in the PCAP question bank. The actual exam draws from this domain proportionally to its weighting in the official exam blueprint.
- What is the best way to practise this domain?
- Start with a short focused session (10 questions) to identify gaps, then work through explanations. Repeat with a longer session once the weak areas feel solid.
- Can I practise only Strings questions?
- Yes — the session launcher on this page filters questions to this domain only. Choose any session length for inline explanations and scoring.