← Course Hub← 课程主页 ← All Units← 返回单元列表
H I G H  S C H O O L  C O M P U T E R  S C I E N C E
Practice练习题

Strings and Text Processing字符串与文本处理

Practice Questions · AP CSP-Feeder · US / ON / BC / AB Styles练习题集 · AP CSP 衔接 · 美 / 安 / 卑 / 阿省风格

EASY MEDIUM HARD 🇺🇸 US 🇨🇦 ON 🇨🇦 BC 🇨🇦 AB AP CSP-style MCQAP CSP 风格选择题 AP CSP-feeder FRQAP CSP 衔接简答题 ON Provincial-style安大略省考风格 BC Provincial-style卑诗省考风格 AB/Universal Applied阿省/通用应用题 Honors荣誉级


Name:姓名:Date:日期:
PART I  ·  SHORT RESPONSE第一部分  ·  短答题AP CSP-style MCQ + ON/BC short answer · 25 marksAP CSP 风格选择题 + 安/卑省考短答 · 共 25 分

Section A · Short ResponseA 部分 · 短答题

Questions mix multiple-choice and short-answer items. For MCQs, circle the letter and show your trace in the work space. For short-answer items, write the exact output. Code is Python; trace each step to verify before answering.本部分包含选择题与短答题。选择题请圈出字母,并在答题空白处写出追踪过程。短答题写出精确输出。代码为 Python;作答前逐步追踪。

Q1 EASY 🇺🇸 US AP CSP-style MCQAP CSP 风格选择题 §1 String Basics and Indexing字符串基础与索引 · CSTA 3A-AP-14 [3 marks][3 分]

Given s = "Python", which expression evaluates to "t"?给定 s = "Python",哪个表达式的值为 "t"

  1. (A) s[1]
  2. (B) s[2]
  3. (C) s[-1]
  4. (D) s[3]
Q2 EASY 🇺🇸 US AP CSP-style MCQAP CSP 风格选择题 §2 String Slicing字符串切片 · AP CSP 3.4 [3 marks][3 分]

What does "computer"[3:6] evaluate to?"computer"[3:6] 的值是什么?

  1. (A) "com"
  2. (B) "put"
  3. (C) "pute"
  4. (D) "mpu"
Q3 EASY 🇨🇦 ON ON Provincial-style安大略省考风格 §3 String Methods and Immutability字符串方法与不可变性 · ICS3U A1.1 [4 marks][4 分]

Consider the following code.考察以下代码。

word = "hello"
word.upper()
print(word)
(a) State the output of print(word).写出 print(word) 的输出。 [1]
(b) Explain in one sentence why word does not change after calling word.upper().用一句话解释为什么调用 word.upper()word 不发生改变。 [2]
(c) Rewrite line 2 so that word stores the uppercased version after the call.重写第 2 行,使 word 在调用后保存大写版本。 [1]
Q4 MEDIUM 🇨🇦 AB AB/Universal Applied阿省/通用应用题 §4 Concatenation and Formatting拼接与格式化 · CSE1110 2.4.6 [7 marks][7 分]

A student writes three programs to produce a grade report line.一名学生编写三个程序,用不同方式产生成绩报告行。

# Program A
name  = "Alex"
score = 88
result_a = "Student: " + name + ", Score: " + score
print(result_a)

# Program B
result_b = "Student: " + name + ", Score: " + str(score)
print(result_b)

# Program C
result_c = f"Student: {name}, Score: {score}"
print(result_c)
(a) Program A raises an error when run. Identify the error type and explain why it occurs.程序 A 运行时会报错。指出错误类型并解释原因。 [2]
(b) Write the exact output of Program B.写出程序 B 的精确输出。 [1]
(c) Write the exact output of Program C. Explain what the f prefix and the {} braces do in an f-string.写出程序 C 的精确输出。解释 f-string 中 f 前缀和 {} 花括号的作用。 [3]
(d) State which style (B or C) is preferred in modern Python and give one reason.说明现代 Python 中更推荐哪种风格(B 或 C),并给出一个理由。 [1]
Q5 MEDIUM 🇨🇦 BC BC Provincial-style卑诗省考风格 §5 Searching Within Strings在字符串中搜索 · AP CSP 3.4 / ICS3C A1.2 [8 marks][8 分]

Use the following variable for all parts.以下所有小题均使用此变量。

sentence = "the quick brown fox"
(a) State the value of "fox" in sentence. State the type of value returned.写出 "fox" in sentence 的值。说明返回值的类型。 [2]
(b) State the value of sentence.find("quick") and of sentence.find("cat"). Explain the meaning of each result.写出 sentence.find("quick")sentence.find("cat") 的值。解释每个结果的含义。 [3]
(c) State the value of sentence.count("o"). Explain which characters are counted.写出 sentence.count("o") 的值。解释哪些字符被计数。 [2]
(d) When should you use in rather than find() for a search? Give one reason.什么情况下搜索应使用 in 而不是 find()?给出一个理由。 [1]
PART II  ·  EXTENDED RESPONSE第二部分  ·  简答题AP CSP-feeder FRQ + Honors · 31 marksAP CSP 衔接简答题 + 荣誉级 · 共 31 分

Section B · Extended ResponseB 部分 · 简答题

Show every step of your trace. Write Python clearly, with correct indentation. For explain/justify questions, two sentences of reasoning earn full marks. No calculator needed; trace by hand.写出每一步追踪过程。Python 须清晰书写,缩进正确。论证题两句推理即可满分。无需计算器;手工追踪。

Q6 MEDIUM 🇺🇸 US AP CSP-feeder FRQAP CSP 衔接简答题 §6 Looping Over Characters遍历字符 · CSTA 3A-AP-14 [8 marks][8 分]

Study the two programs below. Both count vowels in the word "education".研究以下两个程序,均用于计算单词 "education" 中的元音字母数量。

Program A (for-each style):程序 A(for-each 风格):

word   = "education"
vowels = "aeiou"
count  = 0
for ch in word:
    if ch in vowels:
        count += 1
print(count)

Program B (for-range style):程序 B(for-range 风格):

word   = "education"
vowels = "aeiou"
count  = 0
for i in range(len(word)):
    if word[i] in vowels:
        count += 1
print(count)
(a) Trace Program A. List every character in "education" and whether it is a vowel. State the final output.追踪程序 A。列出 "education" 中的每个字符,并注明是否为元音。写出最终输出。 [3]
(b) State what len(word) returns and what values i takes during Program B.写出 len(word) 的返回值,以及程序 B 执行过程中 i 的所有取值。 [2]
(c) Both programs produce the same output. Explain when you would choose Program B (for-range) over Program A (for-each) in a real task. Give one specific example.两个程序产生相同的输出。解释在实际任务中何时选择程序 B(for-range)而不是程序 A(for-each)。举一个具体例子。 [3]
Q7 MEDIUM 🇨🇦 ON ON Provincial-style安大略省考风格 §3 + §5 Methods + Searching方法 + 搜索 · ICS3C A1.2 [8 marks][8 分]

A student normalises and analyses a messy CSV field.一名学生规范化并分析一个杂乱的 CSV 字段。

row    = "  Alice , Biology , 92 "
fields = row.split(",")
clean  = [f.strip().lower() for f in fields]
print(clean)
print(clean[0].count("l"))
print("bio" in clean[1])
(a) State the value of fields immediately after line 2.写出第 2 行之后 fields 的值。 [2]
(b) State the value of clean after line 3. Explain what strip() and lower() each do to the first element.写出第 3 行之后 clean 的值。说明 strip()lower() 分别对第一个元素做了什么。 [3]
(c) State the values printed by lines 4, 5, and 6.写出第 4、5、6 行分别打印的值。 [3]
Q8 HARD 🇨🇦 BC 🇺🇸 US AP CSP-feeder FRQAP CSP 衔接简答题 §2 + §6 Slicing + loop reversal切片 + 循环反转 · AP CSP 4.B [8 marks][8 分]

A student explores two ways to reverse a string.一名学生在探索反转字符串的两种方法。

Method 1 (slice step):方法 1(切片步长):

s    = "racecar"
rev1 = s[::-1]
print(rev1)

Method 2 (character loop):方法 2(字符循环):

s    = "racecar"
rev2 = ""
for ch in s:
    rev2 = ch + rev2
print(rev2)
(a) State the output of Method 1. Explain what the slice [::-1] means (start, stop, step).写出方法 1 的输出。解释切片 [::-1] 的含义(start、stop、step)。 [3]
(b) Trace Method 2 step by step, showing the value of rev2 after each iteration. State the final output.逐步追踪方法 2,写出每次迭代后 rev2 的值。写出最终输出。 [4]
(c) Write a single Python expression (no loop) that evaluates to True if s is a palindrome.写出一个 Python 单行表达式(不用循环),当 s 是回文时值为 True [1]
Q9 HARD Honors荣誉级 🇺🇸 US AP CSP-feeder FRQAP CSP 衔接简答题 §7 Text-Processing Pipeline文本处理流水线 · ICS3C A1.2 / CSE1120 2.6 [7 marks][7 分]

A program processes a sentence using the full text-processing pipeline.一个程序使用完整的文本处理流水线处理一个句子。

sentence = "The cat sat on the mat and the cat"
text  = sentence.lower().strip()
words = text.split()
total = len(words)
freq  = {}
for w in words:
    if w in freq:
        freq[w] += 1
    else:
        freq[w] = 1
top = max(freq, key=freq.get)
print(f"Total words: {total}")
print(f"Most frequent: '{top}' ({freq[top]} times)")
print(f"'cat' appears: {'yes' if 'cat' in words else 'no'}")
(a) State the value of text after line 2 and the value of words after line 3.写出第 2 行后 text 的值和第 3 行后 words 的值。 [2]
(b) State the value of total and write the complete contents of freq after the loop.写出 total 的值,以及循环结束后 freq 的完整内容。 [3]
(c) Write the three lines of output produced by the three print statements.写出三个 print 语句产生的三行输出。 [2]
PART III  ·  MODELING / APPLIED第三部分  ·  建模与应用Universal / multi-region applied · 25 marks通用/多地区应用题 · 共 25 分

Section C · Modeling and ApplicationsC 部分 · 建模与应用

Read each scenario carefully before writing code or traces. Where Python is requested, show correct indentation. Conclude each question with a one-sentence answer. No EASY questions in Part III.动笔前仔细阅读每个场景。Python 须正确缩进。每题以一句完整的结论句作答。第三部分无易级题目。

Q10 MEDIUM 🇺🇸 US 🇨🇦 ON AP CSP-feeder FRQAP CSP 衔接简答题 §5 + §6 Searching + traversal搜索 + 遍历 · ICS3C A1.2 [8 marks][8 分]

A program counts uppercase letters in a string and reports whether the digit "5" is present.一个程序统计字符串中大写字母的数量,并报告数字 "5" 是否存在。

text = "Hello5World"
upper_count = 0
for ch in text:
    if ch.isupper():
        upper_count += 1
print(upper_count)
print("5" in text)
(a) Trace the loop for each character in "Hello5World". Record whether ch.isupper() is True and the running value of upper_count."Hello5World" 的每个字符追踪循环,记录 ch.isupper() 是否为 True 及 upper_count 的累计值。 [4]
(b) State the two values output by the program.写出程序输出的两个值。 [2]
(c) Rewrite the loop body as a single line using sum() and a generator expression so the same count is produced without an explicit loop. Write the single line.sum() 和生成器表达式将循环体改写为一行,无需显式循环。写出这一行。 [2]
Q11 MEDIUM 🇨🇦 ON 🇨🇦 BC ON Provincial-style安大略省考风格 §1 + §2 + §4 Indexing + Slicing + Formatting索引 + 切片 + 格式化 · ICS3U A1.1 [9 marks][9 分]

A program parses a date in "YYYY-MM-DD" format and produces a human-readable report.一个程序解析 "YYYY-MM-DD" 格式的日期并生成人性化报告。

date      = "2024-06-15"
year      = date[0:4]
month     = date[5:7]
day       = date[8:10]
last_char = date[-1]
report    = f"Year: {year}, Month: {month}, Day: {day}, Last char: {last_char}"
print(report)
(a) State the values of year, month, and day after lines 2, 3, and 4.写出第 2、3、4 行后 yearmonthday 的值。 [3]
(b) State the value of last_char. Explain how negative indexing works to retrieve it.写出 last_char 的值。解释负索引如何取得它。 [2]
(c) Write the exact output of print(report).写出 print(report) 的精确输出。 [2]
(d) A student writes date[0] = "3" to change the first digit. This raises a TypeError. Explain why, and state how they should instead produce a corrected date string.一名学生写 date[0] = "3" 来修改第一位,但这会引发 TypeError。解释原因,并说明如何产生修改后的日期字符串。 [2]
Q12 HARD 🇺🇸 US 🇨🇦 ON 🇨🇦 BC AP CSP-feeder FRQAP CSP 衔接简答题 §3 + §5 + §7 Methods + Search + Pipeline debugging方法 + 搜索 + 流水线调试 · CSTA 3A-AP-14 [8 marks][8 分]

A student writes a program to check (case-insensitively) whether a target word appears in a sentence and print how many times it occurs. The program contains a bug.一名学生编写了一个程序,不区分大小写地检查目标词是否出现在句子中并打印次数。该程序存在错误。

sentence = "The Quick Brown Fox"
target   = "the"
if target in sentence:
    print("Found!")
    print(sentence.count(target))
else:
    print("Not found.")
(a) State the current output of the program. Identify the bug: explain why the check on line 3 fails to find "the" in sentence.写出程序当前的输出。找出错误:解释为什么第 3 行的检查在 sentence 中找不到 "the" [3]
(b) Fix the bug. Write the corrected code (minimum change) so the search is case-insensitive and the count is correct.修复错误。写出修改后的代码(最小改动),使搜索不区分大小写且计数正确。 [3]
(c) After fixing the bug, state the correct output for the given sentence and target.修复错误后,对给定的 sentencetarget,写出正确的输出。 [2]

🇺🇸 US CSTA / AP CSP美国 CSTA / AP CSP3A-AP-14 · 3.4 · 4.B
🇨🇦 Ontario安大略ICS3C A1.2 · ICS3U A1.1
🇨🇦 British Columbia不列颠哥伦比亚CS 11 / APCSP: string ops, searching, text algorithmsCS 11 / APCSP:字符串操作、搜索、文本算法
🇨🇦 Alberta阿尔伯塔CSE1110 outcomes 2.4.3, 2.4.6; CSE1120 outcome 2.6CSE1110 结果 2.4.3、2.4.6;CSE1120 结果 2.6

Full Syllabus Map in Study Guide: ../Study Guides/Unit_6_Strings_and_Text_Processing.html. CS has no AB standalone diploma exam; AB framing uses CSE1110/CSE1120 outcomes.完整大纲对照见学习指南:../Study Guides/Unit_6_Strings_and_Text_Processing.html。CS 无独立 AB 毕业考;AB 题使用 CSE1110/CSE1120 结果框架。