Courseiva
Knowledge + Practice
CertificationsVendorsCareer RoadmapsLabs & ToolsStudy GuidesGlossaryPractice Questions
C
Courseiva

Free IT certification practice questions with explained answers for CCNA, CompTIA, AWS, Azure, Google Cloud, and more.

Certification Practice Questions

CCNA practice questionsSecurity+ SY0-701 practice questionsAWS SAA-C03 practice questionsAZ-104 practice questionsAZ-900 practice questionsCLF-C02 practice questionsA+ Core 1 practice questionsGoogle Cloud ACE practice questionsCySA+ CS0-003 practice questionsNetwork+ N10-009 practice questions
View all certifications →

Product

CertificationsCertification PathsExam TopicsPractice TestsExam Dumps vs Practice TestsStudy HubComparisons

Company

AboutContactEditorial PolicyQuestion Writing PolicyTrust Center

Legal

Privacy PolicyTerms of Service

Courseiva is a free IT certification practice platform offering original exam-style practice questions, detailed explanations, topic-based practice, mock exams, readiness tracking, and study analytics for Cisco, CompTIA, Microsoft, AWS, and other technology certifications.

© 2026 Courseiva. Courseiva is operated by JTNetSolutions Ltd. All rights reserved.

Courseiva is an independent certification practice platform and is not affiliated with, endorsed by, or sponsored by Cisco, Microsoft, AWS, CompTIA, Google, ISC2, ISACA, or any other certification vendor. Vendor names and certification marks are used only to identify the exams learners are preparing for.

← Strings practice sets

PCAP Strings • Complete Question Bank

PCAP Strings — All Questions With Answers

Complete PCAP Strings question bank — all 0 questions with answers and detailed explanations.

177
Questions
Free
No signup
Certifications/PCAP/Practice Test/Strings/All Questions
Question 1mediummultiple choice
Read the full Strings explanation →

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

Question 2mediummultiple choice
Read the full Strings explanation →

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

Question 3hardmultiple choice
Read the full NAT/PAT explanation →

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?

Question 4easymultiple choice
Read the full Strings explanation →

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

Question 5mediummultiple choice
Read the full Strings explanation →

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?

Question 6hardmultiple choice
Read the full Strings explanation →

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

Question 7easymultiple choice
Read the full Strings explanation →

Which of the following is the correct way to format a string with variables?

Question 8mediummultiple choice
Study the full Python automation breakdown →

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

Question 9hardmultiple choice
Read the full Strings explanation →

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

Question 10mediummulti select
Study the full Python automation breakdown →

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

Question 11mediummulti select
Study the full Python automation breakdown →

Which TWO statements are true regarding strings in Python?

Question 12hardmulti select
Study the full Python automation breakdown →

Which THREE are valid escape sequences in Python strings?

Question 13hardmulti select
Read the full Strings explanation →

Which THREE methods return a boolean value?

Question 14mediummultiple choice
Read the full Strings explanation →

What is the length of string s?

Exhibit

Refer to the exhibit.

Error log:
```
Traceback (most recent call last):
  File "test.py", line 3, in <module>
    print(s[15])
IndexError: string index out of range
```

Code:
```python
s = "Python Programming"
print(s[15])
```
Question 15hardmultiple choice
Read the full Strings explanation →

What is the value of matches?

Exhibit

Refer to the exhibit.

Configuration block:
```python
import re
pattern = r'\b[A-Z][a-z]*\b'
text = "Alice and Bob are friends."
matches = re.findall(pattern, text)
```
Question 16hardmultiple choice
Review the full routing breakdown →

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?
Question 17mediummultiple choice
Read the full Strings explanation →

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?

Question 18mediummultiple choice
Read the full Strings explanation →

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?

Question 19easymultiple choice
Read the full Strings explanation →

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

Question 20hardmultiple choice
Read the full Strings explanation →

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?

Question 21mediummultiple choice
Read the full NAT/PAT explanation →

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

Question 22easymultiple choice
Read the full Strings explanation →

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

Question 23hardmultiple choice
Read the full Strings explanation →

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?

Question 24mediummultiple choice
Read the full Strings explanation →

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

Question 25mediummulti select
Read the full Strings explanation →

Which TWO of the following methods return a boolean value?

Question 26hardmulti select
Study the full Python automation breakdown →

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

Question 27easymulti select
Study the full Python automation breakdown →

Which TWO of the following are immutable in Python?

Question 28mediummultiple choice
Read the full Strings explanation →

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

Exhibit

s = 'Python Programming'
print(s[7:])
Question 29hardmultiple choice
Read the full Strings explanation →

Refer to the exhibit. What is the output?

Exhibit

text = 'Hello, World!'
result = text.replace('Hello', 'Hi').upper()
print(result)
Question 30hardmultiple choice
Read the full Strings explanation →

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?

Question 31easymultiple choice
Read the full Strings explanation →

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

Question 32mediummultiple choice
Read the full Strings explanation →

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

Question 33hardmultiple choice
Read the full Strings explanation →

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?

Question 34mediummulti select
Study the full Python automation breakdown →

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

Question 35hardmultiple choice
Read the full Strings explanation →

What is the output of the code?

Exhibit

Refer to the exhibit.

```python
import re
pattern = r'\b\w+@\w+\.\w+\b'
text = 'Contact us: support@example.com or sales@example.org.'
matches = re.findall(pattern, text)
print(matches)
```
Question 36mediummultiple choice
Read the full Strings explanation →

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

Question 37mediumdrag order
Study the full Python automation breakdown →

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

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

Steps
Order
1Step 1
2Step 2
3Step 3
4Step 4
5Step 5
Question 38mediumdrag order
Study the full Python automation breakdown →

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

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

Steps
Order
1Step 1
2Step 2
3Step 3
4Step 4
5Step 5
Question 39mediumdrag order
Study the full Python automation breakdown →

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
1Step 1
2Step 2
3Step 3
4Step 4
5Step 5
Question 40mediummatching
Read the full Strings explanation →

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

Question 41mediummatching
Read the full Strings explanation →

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

Question 42mediummatching
Read the full Strings explanation →

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)

Question 43easymultiple choice
Read the full Strings explanation →

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

Question 44easymultiple choice
Read the full Strings explanation →

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

Question 45easymultiple choice
Read the full Strings explanation →

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

Question 46mediummultiple choice
Read the full Strings explanation →

A function receives a string and needs to return a new string with all vowels removed. Which code snippet accomplishes this efficiently?

Question 47mediummultiple choice
Read the full Strings explanation →

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

Question 48mediummultiple choice
Study the full Python automation breakdown →

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

Question 49hardmultiple choice
Read the full Strings explanation →

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

Question 50hardmultiple choice
Read the full Strings explanation →

Which of the following expressions raises a ValueError?

Question 51hardmultiple choice
Study the full Python automation breakdown →

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

Question 52easymulti select
Study the full Python automation breakdown →

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

Question 53mediummulti select
Study the full Python automation breakdown →

Which THREE of the following are true about Python strings?

Question 54hardmulti select
Read the full Strings explanation →

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

Question 55easymultiple choice
Read the full Strings explanation →

Refer to the exhibit. What type of value is printed?

Exhibit

Consider the following Python code:

s = 'Python Programming'
print(s.split())
Question 56mediummultiple choice
Read the full Strings explanation →

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

Exhibit

Error log:

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    print('Hello' + 5)
TypeError: can only concatenate str (not "int") to str
Question 57hardmultiple choice
Read the full Strings explanation →

Refer to the exhibit. What is the output?

Exhibit

Configuration snippet:

import json
policy_string = '{"allow": true, "rate": 100}'
parsed = json.loads(policy_string)
print(parsed['rate'])
Question 58mediummultiple choice
Read the full Strings explanation →

A developer needs to extract the domain name (e.g., 'example.com') from an email address stored in the variable 'email'. The code currently uses `email.split('@')[1]`, which returns the domain part. However, it fails for addresses containing an '@' character in the local part (e.g., 'user@name@domain.com'). Which approach correctly extracts the domain assuming the email is valid?

Question 59easymultiple choice
Study the full Python automation breakdown →

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

Question 60hardmultiple choice
Read the full Strings explanation →

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

Question 61mediummultiple choice
Read the full Strings explanation →

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

Question 62easymultiple choice
Read the full Strings explanation →

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?

Question 63mediummultiple choice
Read the full Strings explanation →

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

Question 64hardmultiple choice
Read the full Strings explanation →

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?

Question 65easymultiple choice
Read the full Strings explanation →

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

Question 66mediummultiple choice
Study the full Python automation breakdown →

Given `s = 'Python'`, what is the result of `s[-4::-1]`?

Question 67mediummulti select
Read the full Strings explanation →

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

Question 68hardmulti select
Study the full Python automation breakdown →

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

Question 69easymulti select
Read the full Strings explanation →

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

Question 70easymultiple choice
Read the full Strings explanation →

What is the output of the above code?

Exhibit

Refer to the exhibit.

```
# File: config.py
name = "Alice"
age = 30
print(f"{name} is {age} years old.")
```
Question 71mediummultiple choice
Read the full Strings explanation →

What is the cause of the error?

Exhibit

Refer to the exhibit.

```
# Error log
Traceback (most recent call last):
  File "server.py", line 45, in <module>
    message = "Welcome " + username.encode('utf-8') + "!"
TypeError: can only concatenate str (not "bytes") to str
```
Question 72hardmultiple choice
Read the full Strings explanation →

What is the output of the code?

Exhibit

Refer to the exhibit.

```
# Code snippet
import json

data = {'name': 'Alice', 'age': 30, 'city': 'New York'}
json_str = json.dumps(data, indent=2)
print(json_str.split('\n')[2])
```
Question 73easymultiple choice
Read the full Strings explanation →

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

Question 74easymultiple choice
Read the full Strings explanation →

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

Question 75easymultiple choice
Study the full Python automation breakdown →

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

Question 76mediummultiple choice
Read the full Strings explanation →

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?

Question 77mediummultiple choice
Study the full Python automation breakdown →

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

Question 78mediummultiple choice
Read the full Strings explanation →

Which of the following demonstrates that strings are immutable?

Question 79hardmultiple choice
Study the full Python automation breakdown →

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

Question 80hardmultiple choice
Read the full NAT/PAT explanation →

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

Question 81hardmultiple choice
Read the full Strings explanation →

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

Question 82easymulti select
Read the full Strings explanation →

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

Question 83mediummulti select
Study the full Python automation breakdown →

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

Question 84hardmulti select
Study the full Python automation breakdown →

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

Question 85easymultiple choice
Read the full Strings explanation →

Refer to the exhibit. What is the output?

Exhibit

text = "  Python programming  "
result = text.strip()
print(len(result))
Question 86mediummultiple choice
Read the full Strings explanation →

Refer to the exhibit. What is printed?

Exhibit

name = "Alice"
age = 25
txt = f"{name:>10} is {age:03d} years old."
print(txt)
Question 87hardmultiple choice
Read the full Strings explanation →

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

Exhibit

filepath = "C:\Users\Admin\Documents\file.txt"
with open(filepath, 'r') as f:
    content = f.read()
Question 88mediummultiple choice
Read the full Strings explanation →

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?

Question 89hardmultiple choice
Read the full NAT/PAT explanation →

In a data processing pipeline, a string variable 'text' contains the value "Hello\nWorld\r\n". The developer needs to count the number of lines in the text. Which expression returns the correct line count (treating \n and \r\n as line terminators)?

Question 90easymultiple choice
Study the full Python automation breakdown →

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

Question 91mediummultiple choice
Study the full Python automation breakdown →

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

Question 92hardmultiple choice
Study the full Python automation breakdown →

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

Question 93easymultiple choice
Study the full Python automation breakdown →

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

Question 94mediummultiple choice
Read the full Strings explanation →

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

Question 95hardmultiple choice
Read the full Strings explanation →

Consider the following code: result = ' '.join(['a', 'b', 'c'])

print(repr(result))

What is the output?

Question 96easymultiple choice
Read the full Strings explanation →

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

Question 97mediummulti select
Study the full Python automation breakdown →

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

Question 98hardmulti select
Study the full Python automation breakdown →

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

Question 99easymulti select
Study the full Python automation breakdown →

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

Question 100mediummultiple choice
Read the full Strings explanation →

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?

Question 101easymultiple choice
Read the full Strings explanation →

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

Question 102hardmultiple choice
Study the full Python automation breakdown →

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?

Question 103mediummultiple choice
Read the full Strings explanation →

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

Question 104easymultiple choice
Read the full Strings explanation →

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

Question 105hardmultiple choice
Read the full NAT/PAT explanation →

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?

Question 106mediummultiple choice
Read the full Strings explanation →

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

Question 107easymultiple choice
Read the full Strings explanation →

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

Question 108hardmultiple choice
Read the full Strings explanation →

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?

Question 109mediummulti select
Read the full Strings explanation →

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

Question 110hardmulti select
Study the full Python automation breakdown →

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

Question 111easymulti select
Read the full Strings explanation →

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

Question 112easymultiple choice
Read the full Strings explanation →

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

Question 113mediummultiple choice
Study the full Python automation breakdown →

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?

Question 114hardmultiple choice
Read the full Strings explanation →

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

Question 115mediummulti select
Read the full Strings explanation →

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

Question 116easymultiple choice
Study the full Python automation breakdown →

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

Question 117mediummultiple choice
Study the full Python automation breakdown →

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

Question 118hardmulti select
Study the full Python automation breakdown →

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

Question 119easymultiple choice
Read the full Strings explanation →

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

Question 120hardmultiple choice
Study the full Python automation breakdown →

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

Question 121mediummultiple choice
Read the full Strings explanation →

What will the above code output?

Exhibit

Refer to the exhibit.

s = "hello world"
try:
    print(s[100])
except IndexError:
    print("Index out of range")
Question 122easymultiple choice
Read the full Strings explanation →

What is the output of the code in the exhibit?

Exhibit

Refer to the exhibit.

name = "Alice"
age = 30
print(f"{name} is {age} years old.")
Question 123hardmultiple choice
Read the full Strings explanation →

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

Exhibit

Refer to the exhibit.

path = r"C:\Users\John\Documents"
print(len(path))
Question 124mediummulti select
Read the full Strings explanation →

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

Question 125hardmultiple choice
Read the full Strings explanation →

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

Question 126easymultiple choice
Read the full Strings explanation →

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?

Question 127easymultiple choice
Read the full Strings explanation →

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?

Question 128mediummultiple choice
Read the full Strings explanation →

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?

Question 129mediummultiple choice
Read the full Strings explanation →

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

Question 130easymultiple choice
Read the full Strings explanation →

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

Question 131mediummultiple choice
Read the full Strings explanation →

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

Question 132hardmultiple choice
Study the full Python automation breakdown →

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

Question 133hardmultiple choice
Read the full Strings explanation →

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

Question 134hardmultiple choice
Read the full Strings explanation →

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

Question 135easymultiple choice
Read the full Strings explanation →

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

Question 136easymulti select
Study the full Python automation breakdown →

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

Question 137mediummulti select
Read the full Strings explanation →

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

Question 138hardmulti select
Study the full Python automation breakdown →

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

Question 139easymultiple choice
Read the full Strings explanation →

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

Exhibit

s = "Python PCAP"
print(s[0:6:2])
Question 140mediummultiple choice
Read the full Strings explanation →

Refer to the exhibit. What is the output?

Exhibit

s = "Hello World"
try:
    s[12] = 'x'
except TypeError:
    print("TypeError")
except IndexError:
    print("IndexError")
Question 141hardmultiple choice
Study the full Python automation breakdown →

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

Exhibit

$ python -c "import re; print(re.split(r'\s+', 'one   two three'))"
Question 142easymultiple choice
Read the full Strings explanation →

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

Question 143easymultiple choice
Read the full Strings explanation →

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

Question 144easymultiple choice
Read the full Strings explanation →

Which expression returns the last character of string s?

Question 145mediummultiple choice
Study the full Python automation breakdown →

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

Question 146mediummultiple choice
Study the full Python automation breakdown →

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

Question 147mediummultiple choice
Read the full Strings explanation →

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

Question 148hardmultiple choice
Read the full Strings explanation →

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?

Question 149hardmultiple choice
Read the full Strings explanation →

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

Question 150hardmultiple choice
Read the full Strings explanation →

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

Question 151easymulti select
Read the full Strings explanation →

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

Question 152mediummulti select
Read the full Strings explanation →

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

Question 153hardmulti select
Study the full Python automation breakdown →

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

Question 154easymultiple choice
Read the full Strings explanation →

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?

Question 155mediummultiple choice
Read the full Strings explanation →

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?

Question 156hardmultiple choice
Study the full Python automation breakdown →

A DevOps engineer is writing a Python script to parse a configuration file. The file contains lines like: 'PARAMETER = value'. The engineer needs to extract the value part after the '=' sign, but there may be multiple equals signs in the value (e.g., 'DATABASE = mysql://user:pass@host/db'). The engineer initially uses line.split('=')[1] but this fails if there are extra equals. Which of the following approaches correctly extracts everything after the first '=' sign?

Question 157easymultiple choice
Read the full NAT/PAT explanation →

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?

Question 158mediummultiple choice
Read the full Strings explanation →

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?

Question 159hardmultiple choice
Read the full Strings explanation →

A function processes a Unicode string that may contain combining characters (e.g., 'é' as 'e' plus combining acute accent). The function must return the number of visible grapheme clusters (user-perceived characters). Which of the following is the most reliable built-in approach?

Question 160easymulti select
Read the full Strings explanation →

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

Question 161mediummulti select
Study the full Python automation breakdown →

Which THREE of the following are immutable types in Python?

Question 162hardmulti select
Read the full NAT/PAT explanation →

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

Question 163easymultiple choice
Read the full Strings explanation →

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?

Question 164easymultiple choice
Study the full Python automation breakdown →

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?

Question 165easymultiple choice
Study the full Python automation breakdown →

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

Question 166mediummultiple choice
Read the full Strings explanation →

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?

Question 167mediummultiple choice
Study the full Python automation breakdown →

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

Question 168mediummultiple choice
Read the full Strings explanation →

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?

Question 169hardmultiple choice
Read the full Strings explanation →

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?

Question 170hardmultiple choice
Study the full AAA explanation →

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

Question 171hardmultiple choice
Study the full Python automation breakdown →

A developer has a string that contains literal escape sequences like '\\n' and '\\t' (i.e., a backslash followed by 'n' or 't') and needs to convert them into actual control characters (newline, tab). The string comes from a configuration file that was written with double backslashes to represent single backslashes in the original configuration. The developer wants to use standard Python functionality. For example, the string "hello\\nworld" should become "hello\nworld" (a string with a real newline). Which of the following is the simplest and most reliable method?

Question 172mediummulti select
Study the full Python automation breakdown →

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

Question 173hardmultiple choice
Study the full Python automation breakdown →

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?

Question 174easymultiple choice
Study the full Python automation breakdown →

A developer is building an IoT application that reads temperature data from a sensor over a TCP socket. The sensor sends data as a stream of bytes encoded in UTF-8, with each reading terminated by a newline character. The developer uses the following code to receive data:

```python

import socket

s = socket.socket() s.connect(('sensor.local', 5000)) data = s.recv(1024) ```

The variable `data` is a bytes object. The developer needs to convert it to a string to parse the temperature value. Which of the following lines of code should the developer use to correctly obtain the string representation of the received data, assuming the data is valid UTF-8 and may contain non-ASCII characters?

Question 175easymulti select
Read the full Strings explanation →

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

Question 176mediummultiple choice
Read the full Strings explanation →

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

Exhibit

>>> s = "Hello"
>>> s[1] = "a"
Question 177hardmultiple choice
Read the full NAT/PAT explanation →

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?

Practice tests

Scored 10-question sessions with instant feedback and explanations.

PCAP Practice Test 1 — 10 Questions→PCAP Practice Test 2 — 10 Questions→PCAP Practice Test 3 — 10 Questions→PCAP Practice Test 4 — 10 Questions→PCAP Practice Test 5 — 10 Questions→PCAP Practice Exam 1 — 20 Questions→PCAP Practice Exam 2 — 20 Questions→PCAP Practice Exam 3 — 20 Questions→PCAP Practice Exam 4 — 20 Questions→Free PCAP Practice Test 1 — 30 Questions→Free PCAP Practice Test 2 — 30 Questions→Free PCAP Practice Test 3 — 30 Questions→PCAP Practice Questions 1 — 50 Questions→PCAP Practice Questions 2 — 50 Questions→PCAP Exam Simulation 1 — 100 Questions→

Practice by domain

Each domain maps to a weighted exam section. Focus on the domain where you are weakest.

Modules and PackagesStringsObject-Oriented ProgrammingExceptions and File I/O

Practice by scenario

Filter questions by type — troubleshooting, exhibit, drag-and-drop, PBQ, ACLs, OSPF, and more.

Browse scenarios→

Continue studying

All Strings setsAll Strings questionsPCAP Practice Hub