Strings and Text Processing字符串与文本处理
A string is a sequence of characters, every piece of text your program touches is a string. This guide builds from the ground up: how strings are indexed and sliced in Python, which built-in methods (upper, lower, split, join, replace) do the heavy lifting, how concatenation and f-strings produce formatted output, how to search inside a string with in, find, and count, how to loop character by character, and how to combine these tools in a complete text-processing program. All code is Python; bilingual explanations throughout.字符串(string,字符串)是字符(character,字符)的序列,程序处理的每一段文本都是字符串。本指南从基础讲起:Python 中字符串的索引(index,索引)和切片(slicing,切片)、哪些内置方法(method,方法)承担重活(upper、lower、split、join、replace)、如何用拼接(concatenation,拼接)和 f-string 生成格式化(formatting,格式化)输出、如何用 in、find、count 在字符串中搜索、如何逐字符遍历,以及如何将这些工具组合成完整的文本处理(text processing,文本处理)程序。全部代码为 Python;全篇双语说明。
String Basics and Indexing字符串基础与索引
- State that a string is a sequence of characters and read one character with
s[i]using positive and negative indices. - Predict
s[i],s[-i]andlen(s)for a given string, including the first and last characters. - Explain why an index of
len(s)raises anIndexErrorand whys[0] = "X"raises aTypeError. - Build a changed version of a string by creating a new string, because strings are immutable.
- 说明字符串是字符的序列,并用
s[i]的正索引和负索引读取单个字符。 - 对给定字符串预测
s[i]、s[-i]和len(s),包括第一个和最后一个字符。 - 解释为什么索引取
len(s)会引发IndexError,以及为什么s[0] = "X"会引发TypeError。 - 因为字符串不可变,通过创建新字符串来得到修改后的版本。
- A string is a sequence of characters.字符串是字符的序列。 Every character (a letter, digit, space or punctuation mark) is stored at a numbered position called an index. Indices start at
0, not 1.每个字符(字母、数字、空格或标点)都存储在一个称为索引的编号位置。索引从0开始,不是 1。 - Read one character with bracket notation.用方括号表示法读取单个字符。
s[0]is the first character;s[-1]is the last character;s[-2]is the second-to-last.s[0]是第一个字符;s[-1]是最后一个字符;s[-2]是倒数第二个字符。 - Strings are immutable.字符串是不可变的。 You cannot change a character in place (
s[0] = "X"raises a TypeError). Every "modification" creates a new string object.你无法就地修改字符(s[0] = "X"会引发 TypeError)。每次"修改"都会创建一个新的字符串对象。
Worked Example 1: Indexing into a string例题 1:字符串索引
Predict the output of each line without running the code.不运行代码,预测每行的输出。
name = "Dingrui"
print(name[0]) # D
print(name[3]) # g
print(name[-1]) # i
print(name[-3]) # r
print(len(name)) # 7
Index map: D=0, i=1, n=2, g=3, r=4, u=5, i=6. Negative indices count from the right: -1 is i, -2 is u, -3 is r, so name[-3] prints r. len("Dingrui") is 7, so the last valid index is 6.索引对应:D=0, i=1, n=2, g=3, r=4, u=5, i=6。负索引从右数起:-1 是 i,-2 是 u,-3 是 r,因此 name[-3] 输出 r。len("Dingrui") 为 7,所以最后一个有效索引是 6。
Worked Example 2: Index errors and immutability例题 2:索引错误与不可变性
Given word = "Python", predict each printed value, say which index expressions would fail and why, then "change" the first letter to J without altering word.给定 word = "Python",预测每个输出值,指出哪些索引表达式会失败及原因,然后在不改动 word 的前提下把首字母"改"成 J。
word = "Python"
print(word[0], word[5]) # P n
print(word[-1], word[-6]) # n P
print(len(word)) # 6
print(word[len(word) - 1]) # n
# word[6] would raise IndexError: string index out of range
# word[0] = "J" raises TypeError (strings are immutable)
new_word = "J" + word[1:]
print(new_word) # Jython
print(word) # Python
Index map: P=0, y=1, t=2, h=3, o=4, n=5 and, from the right, n=-1, o=-2, h=-3, t=-4, y=-5, P=-6. The length is 6, so the valid indices are 0 to 5 (or -6 to -1). That is why word[len(word) - 1] is the last character and word[6] is out of range. Assigning to word[0] fails because a string cannot be changed in place; instead word[1:] (every character from index 1 on, see the next section) is joined to "J" to make a new string. The original is untouched.索引对应:P=0, y=1, t=2, h=3, o=4, n=5;从右数则 n=-1, o=-2, h=-3, t=-4, y=-5, P=-6。长度为 6,所以有效索引是 0 到 5(或 -6 到 -1)。因此 word[len(word) - 1] 是最后一个字符,而 word[6] 越界。给 word[0] 赋值会失败,因为字符串不能就地修改;做法是把 word[1:](从索引 1 开始的所有字符,见下一节)与 "J" 连接成新字符串,原字符串保持不变。
s = "Python", what is s[2]?给定 s = "Python",s[2] 的值是什么?s[2] is "t".索引:P=0, y=1, t=2, h=3, o=4, n=5。因此 s[2] 为 "t"。s = "Hello", what is s[-1]?给定 s = "Hello",s[-1] 的值是什么?-1 always refers to the last character. "Hello" ends in "o", so s[-1] = "o".负索引 -1 始终指向最后一个字符。"Hello" 以 "o" 结尾,因此 s[-1] = "o"。s[-1] = last character = "o". s[0] = "H". Negative indices count from the right: -1 is last, -2 is second-to-last.s[-1] = 最后一个字符 = "o"。s[0] = "H"。负索引从右计数:-1 是最后,-2 是倒数第二。Questions that say state, predict or trace are answered fastest by writing the index under each character first, so an off-by-one slip shows up on paper. Common errors: counting from 1, using s[len(s)] for the last character (it raises an error; use s[len(s) - 1] or s[-1]), forgetting that spaces and punctuation count in len, and writing s.upper() without assigning the result.
遇到state(写出)、predict(预测)或 trace(追踪)类题目,最快的做法是先在每个字符下写出索引,这样差一错误会在纸面上暴露。常见错误:从 1 开始数;用 s[len(s)] 取最后一个字符(会报错,应写 s[len(s) - 1] 或 s[-1]);忘了空格和标点也计入 len;写了 s.upper() 却不把结果赋值。
For s = "banana", state s[0], s[-1], s[-6] and len(s).对 s = "banana",写出 s[0]、s[-1]、s[-6] 和 len(s)。
s[0] is "b"; s[-1] is "a"; s[-6] is "b" (length 6, so -6 is the same position as 0); len(s) is 6.
s[0] 是 "b";s[-1] 是 "a";s[-6] 是 "b"(长度为 6,-6 与 0 是同一位置);len(s) 为 6。
A student writes s = "code" and then print(s[4]). What happens, and which index gives the last character?学生写了 s = "code" 然后 print(s[4])。会发生什么?哪个索引才是最后一个字符?
It raises an IndexError, because the valid indices are 0 to 3 (the length is 4). The last character is s[3], or s[-1].
会引发 IndexError,因为有效索引是 0 到 3(长度为 4)。最后一个字符是 s[3],也可以写 s[-1]。
Why does s = "cat" followed by s[0] = "b" fail? Write one line that makes s equal to "bat".为什么 s = "cat" 后接 s[0] = "b" 会失败?写一行代码使 s 等于 "bat"。
Strings are immutable, so a character cannot be assigned in place; Python raises a TypeError. Build a new string and rebind the name: s = "b" + s[1:], which gives "bat".
字符串不可变,不能就地给某个字符赋值,Python 会引发 TypeError。应构造新字符串并重新绑定变量名:s = "b" + s[1:],得到 "bat"。
String Slicing字符串切片
- Read
s[start:stop],s[:stop],s[start:]ands[start:stop:step], applying the rule that stop is excluded. - Use negative indices and a negative step in a slice, and reverse a string with
s[::-1]. - Calculate the length of a slice (
stop - startwhen the step is 1) and explain why a stop past the end causes no error while a single index does. - Write a slice that extracts a field from fixed-format text such as a date.
- 读懂
s[start:stop]、s[:stop]、s[start:]和s[start:stop:step],并运用"stop 不包含"的规则。 - 在切片中使用负索引和负步长,并用
s[::-1]反转字符串。 - 计算切片的长度(步长为 1 时为
stop - start),并解释为什么 stop 超出末尾不报错而单个索引越界会报错。 - 写出从固定格式文本(如日期)中提取字段的切片。
s[start:stop], includes start, excludes stop.切片语法:s[start:stop],包含 start,不含 stop。
s[1:4]: characters at indices 1, 2, 3 (NOT 4).:索引 1、2、3 处的字符(不含 4)。s[:3]: omit start → defaults to 0. Gives first 3 characters.:省略 start 则默认为 0。返回前 3 个字符。s[2:]: omit stop → goes to end. Gives everything from index 2 onward.:省略 stop 则到末尾。返回从索引 2 开始的全部字符。s[::2]: step of 2 → every other character.s[::-1]reverses the string.:步长为 2 → 每隔一个字符取一个。s[::-1]反转字符串。
s[0:3], not s[0:2]. ON ICS3C A1.2 names "extract a portion of an address"; that is a slice.最容易出错的地方:stop 索引是不包含的。如果你想要位置 0、1、2 处的字符,你写 s[0:3],不是 s[0:2]。ON ICS3C A1.2 点名"提取地址的一部分",那就是切片。
"computer" with its positive index (first row of numbers) and negative index (second row) under each character. The shaded cells are s[2:5]: the slice starts at index 2 (included) and stops at index 5 (excluded), so it returns the characters at indices 2, 3 and 4, which is "mpu". The dashed lines sit on cell boundaries, not on characters. The same slice is s[-6:-3].图 1. 字符串 "computer",每个字符下方依次标出正索引(第一行数字)和负索引(第二行)。阴影格子是 s[2:5]:切片从索引 2 开始(包含),到索引 5 结束(不含),因此返回索引 2、3、4 处的字符,即 "mpu"。虚线位于格子的边界上,而不是字符上。同一切片也可写成 s[-6:-3]。Worked Example 3: Slicing a date string例题 3:切片日期字符串
Given date = "2024-06-15", extract the year, month, and day as separate strings.给定 date = "2024-06-15",将年、月、日提取为单独的字符串。
date = "2024-06-15"
year = date[0:4] # "2024"
month = date[5:7] # "06"
day = date[8:10] # "15"
print(year, month, day) # 2024 06 15
The characters at indices 0 to 9 are 2, 0, 2, 4, -, 0, 6, -, 1, 5. date[0:4] takes indices 0 to 3, which gives "2024". date[5:7] takes indices 5 and 6, which gives "06". date[8:10] takes indices 8 and 9, which gives "15". This is the canonical ON ICS3C A1.2 "extract a portion" operation.以上:date[0:4] 取索引 0~3(共 4 字符),date[5:7] 取索引 5~6,date[8:10] 取索引 8~9。这是 ON ICS3C A1.2"提取地址的一部分"的典型例子。
Worked Example 4: Slice patterns on one string例题 4:同一字符串上的切片模式
Given s = "programming", predict each slice: the first three characters, a middle part, the last four, everything except the last four, every second character, a backward slice, a stop past the end, and an empty slice.给定 s = "programming",预测下列切片:前三个字符、中间一段、最后四个字符、除最后四个以外的全部、每隔一个字符、反向切片、stop 超过末尾,以及空切片。
s = "programming" # p r o g r a m m i n g (indices 0 to 10)
print(s[:3]) # pro
print(s[3:7]) # gram
print(s[-4:]) # ming
print(s[:-4]) # program
print(s[::2]) # pormig
print(s[8:3:-1]) # immar
print(s[2:50]) # ogramming
print(repr(s[5:2])) # ''
print(len(s[3:7])) # 4
Index map: p=0, r=1, o=2, g=3, r=4, a=5, m=6, m=7, i=8, n=9, g=10 (length 11). s[3:7] takes indices 3, 4, 5, 6, so it is "gram" and its length is 7 - 3 = 4. s[-4:] starts four from the right (index 7). s[:-4] stops before that point, so the two pieces s[:-4] and s[-4:] together rebuild the string. A step of 2 from index 0 takes indices 0, 2, 4, 6, 8, 10. s[8:3:-1] walks backward from index 8 down to index 4 (stop 3 is excluded), giving "immar". A stop of 50 is past the end, so Python stops at the end without an error; and s[5:2] is empty because a forward slice cannot start after its stop.索引对应:p=0, r=1, o=2, g=3, r=4, a=5, m=6, m=7, i=8, n=9, g=10(长度 11)。s[3:7] 取索引 3、4、5、6,所以是 "gram",长度为 7 - 3 = 4。s[-4:] 从右数第四个(索引 7)开始。s[:-4] 在这一点之前结束,所以 s[:-4] 与 s[-4:] 合起来恰好还原整个字符串。步长为 2 从索引 0 开始,取索引 0、2、4、6、8、10。s[8:3:-1] 从索引 8 向后走到索引 4(stop 3 不含),得到 "immar"。stop 为 50 超过了末尾,Python 会在末尾停下而不报错;s[5:2] 为空,因为正向切片不能从 stop 之后开始。
s = "computer", what does s[2:5] return?给定 s = "computer",s[2:5] 返回什么?s[2:5] = indices 2,3,4 = "mpu". Stop index 5 is excluded."computer":c=0,o=1,m=2,p=3,u=4,t=5,e=6,r=7。s[2:5] = 索引 2,3,4 = "mpu"。stop 索引 5 不包含。[2:5] gives indices 2, 3, 4, the stop (5) is excluded. "computer"[2]="m", [3]="p", [4]="u" → "mpu".切片 [2:5] 给出索引 2、3、4,stop(5)不包含。"computer"[2]="m",[3]="p",[4]="u" → "mpu"。"Hello"[::-1] return?"Hello"[::-1] 返回什么?-1 reverses the string. "Hello"[::-1] reads every character from right to left: "olleH".步长 -1 会反转字符串。"Hello"[::-1] 从右到左读取每个字符:"olleH"。[::-1] = reverse. Start and stop are omitted (whole string), step is -1 (backwards). Result: "olleH".[::-1] = 反转。start 和 stop 省略(整个字符串),step 为 -1(反向)。结果:"olleH"。For predict and write the slice questions, number the characters first, then circle start and cross out stop. Common errors: using s[0:2] for the first three characters, using s[1:4] and expecting four characters (it gives three), and confusing s[-4] (one character) with s[-4:] (the last four). A single index out of range is an error, but a slice never is.
遇到predict(预测)和write the slice(写出切片)类题目,先给字符编号,然后圈出 start、划掉 stop。常见错误:用 s[0:2] 取前三个字符;用 s[1:4] 却以为得到四个字符(实际是三个);把 s[-4](一个字符)与 s[-4:](最后四个字符)混淆。单个索引越界会报错,而切片从不报错。
For s = "computer", write a slice that returns "put", once with positive indices and once with negative indices.对 s = "computer",写出返回 "put" 的切片,分别用正索引和负索引。
"put" starts at index 3 (p) and ends at index 5 (t), so the stop is 6: s[3:6]. With negative indices the length is 8, so index 3 is -5 and the stop index 6 is -2: s[-5:-2].
"put" 从索引 3(p)开始,到索引 5(t)结束,所以 stop 是 6:s[3:6]。用负索引时长度为 8,索引 3 对应 -5,stop 索引 6 对应 -2:s[-5:-2]。
For any string s, what is s[:3] + s[3:], and why?对任意字符串 s,s[:3] + s[3:] 是什么?为什么?
It is s itself. The first slice stops before index 3 (excluded) and the second starts at index 3 (included), so there is no gap and no overlap.
结果就是 s 本身。第一个切片在索引 3 之前结束(不含),第二个从索引 3 开始(包含),因此没有缺口也没有重叠。
Given date = "2024-06-15", use slices only to build "15/06/2024".给定 date = "2024-06-15",只用切片构造 "15/06/2024"。
The day is date[8:], the month is date[5:7] and the year is date[:4], so date[8:] + "/" + date[5:7] + "/" + date[:4] gives "15/06/2024".
日是 date[8:],月是 date[5:7],年是 date[:4],因此 date[8:] + "/" + date[5:7] + "/" + date[:4] 得到 "15/06/2024"。
String Methods字符串方法
- State what
upper,lower,strip,split,joinandreplaceeach return, and that none of them changes the original string. - Choose between
split()with no argument andsplit(sep), and predict the list each produces. - Chain methods left to right and write the intermediate string after each call.
- Rebuild a line of text from a list with
sep.join(items)and delete characters withreplace(old, ""). - Capitalise the first letter of a word with
capitalize()or withs[0].upper() + s[1:].
- 说明
upper、lower、strip、split、join和replace各自返回什么,以及它们都不会改变原字符串。 - 在不带参数的
split()与split(sep)之间做出选择,并预测各自产生的列表。 - 从左到右进行方法链式调用,并在每次调用后写出中间字符串。
- 用
sep.join(items)从列表重建一行文本,并用replace(old, "")删除字符。 - 用
capitalize()或s[0].upper() + s[1:]把单词首字母大写。
s.upper(): returns a new string with all characters uppercased."hello".upper()→"HELLO".:返回所有字符大写的新字符串。"hello".upper()→"HELLO"。s.lower(): returns all lowercase. Useful for case-insensitive comparison.:返回全小写。用于不区分大小写的比较。s.split(sep): splits onsepand returns a list."a,b,c".split(",")→["a","b","c"]. Ifsepis omitted, splits on any whitespace.:按sep分割并返回列表。"a,b,c".split(",")→["a","b","c"]。省略sep则按任意空白分割。sep.join(iterable): the inverse of split."-".join(["a","b","c"])→"a-b-c".:split 的逆操作。"-".join(["a","b","c"])→"a-b-c"。s.replace(old, new): replaces every occurrence ofoldwithnew."cats and cats".replace("cats","dogs")→"dogs and dogs".:将每个old替换为new。"cats and cats".replace("cats","dogs")→"dogs and dogs"。
s[0].upper() + s[1:] or capitalize(); "extract a portion" → slice + split; "count occurrences" → count() in §5. AB CSE1120 outcome 2.6 names "concatenation and interpolation operators", join() is the idiomatic Python concatenation tool.课程依据:ON ICS3C A1.2(原文):"将首字母大写" → s[0].upper() + s[1:] 或 capitalize();"提取一部分" → 切片 + split;"计算出现次数" → count()(见 §5)。AB CSE1120 结果 2.6 点名"拼接和插值运算符",join() 是 Python 的惯用拼接工具。
Worked Example 5: Normalising a CSV line例题 5:规范化 CSV 行
Given row = " Alice , Biology , 92 ", produce a clean list of stripped, lowercased fields.给定 row = " Alice , Biology , 92 ",生成去空格、小写的字段列表。
row = " Alice , Biology , 92 "
fields = row.split(",") # [' Alice ', ' Biology ', ' 92 ']
clean = [f.strip().lower() for f in fields]
print(clean) # ['alice', 'biology', '92']
以上:split(",") 按逗号分割(方法,method),strip() 去除两端空白,lower() 转为小写。这三个步骤可以链式调用。Chain: split(",") splits on comma (returns list), then strip() removes surrounding whitespace, then lower() normalises case. This pattern, split, strip, lower, is the standard CSV-cleaning idiom.
Worked Example 6: Rebuilding a CSV Line with replace() and join()例题 6:用 replace() 和 join() 重建 CSV 行
Worked Example 5 parsed a row into clean fields. Now do the reverse: given a list of price strings that carry a currency symbol, strip the symbol from each field with replace(), then rebuild a single comma-separated line with join(). Both replace() and join() are named in the §3 cram-cheat but neither has appeared in a worked example until now.例题 5 把一行数据解析成了干净的字段。现在做相反的事:给定一个带货币符号的价格字符串列表,先用 replace() 从每个字段中去除符号,再用 join() 把它们重建成一行以逗号分隔的数据。replace() 和 join() 都在 §3 的速记框中被点名,但直到现在都还没有在例题中出现过。
prices = ["$12", "$5", "$100"]
# Step 1: replace() strips the currency symbol from each field
cleaned = [p.replace("$", "") for p in prices]
print(cleaned) # ['12', '5', '100']
# Step 2: join() rebuilds a single comma-separated line
csv_line = ",".join(cleaned)
print(csv_line) # 12,5,100
以上:replace("$", "") 把货币符号替换为空字符串,也就是删除它;列表推导式对列表中的每个字段重复这个操作。",".join(cleaned) 正是 split(",") 的逆操作:把字段列表重新连接成一行文本,逗号插入相邻字段之间。replace("$", "") substitutes the empty string for the symbol, which is how you delete a character in Python; the list comprehension applies this to every field. ",".join(cleaned) is the exact inverse of split(",") from Worked Example 5: it walks the list once and inserts the separator between adjacent fields, producing a single new string in one pass rather than a manual loop with repeated concatenation.
"Hello World".lower() return?"Hello World".lower() 返回什么?lower() converts every character to lowercase, returning a new string. Spaces are unchanged.lower() 将每个字符转换为小写,返回新字符串。空格不变。lower() lowercases everything. upper() would give "HELLO WORLD". The original string is unchanged because strings are immutable.lower() 将所有字母转为小写。upper() 会得到 "HELLO WORLD"。原字符串不变,因为字符串是不可变的。",".join(["a","b","c"]) return?",".join(["a","b","c"]) 返回什么?join() concatenates the list elements with the separator "," between each pair. Result: "a,b,c".join() 将列表元素用分隔符 "," 连接在一起。结果:"a,b,c"。sep.join(list) produces a string, not a list. The separator goes between each element: "a" + "," + "b" + "," + "c" = "a,b,c".sep.join(list) 产生字符串,不是列表。分隔符位于每个元素之间:"a" + "," + "b" + "," + "c" = "a,b,c"。Method-chain answers are easiest to check when each step is visible, so write the string after every call, working left to right. Common errors: writing s.upper() and expecting s to change (assign the result), using split(" ") when the text has repeated spaces (it returns empty strings; plain split() does not), and forgetting that strip() removes only the ends, not spaces inside the text.
方法链类题目应把每一步都写出来:从左到右,在每次调用后写下当前字符串。常见错误:写了 s.upper() 却以为 s 已改变(需要赋值);文本含连续空格时用 split(" ")(会产生空字符串,而不带参数的 split() 不会);忘记 strip() 只去掉两端而不处理文本内部的空格。
Let s = " Hello ". Evaluate s.strip().lower().replace("h", "j"), writing the string after each call.设 s = " Hello "。计算 s.strip().lower().replace("h", "j"),并写出每次调用后的字符串。
strip() gives "Hello"; lower() gives "hello"; replace("h", "j") gives "jello". The result is "jello" and s itself is unchanged.
strip() 得到 "Hello";lower() 得到 "hello";replace("h", "j") 得到 "jello"。结果是 "jello",s 本身不变。
What do "a b".split(" ") and "a b".split() return? (There are two spaces between a and b.)"a b".split(" ") 和 "a b".split() 各返回什么?(a 和 b 之间有两个空格。)
split(" ") cuts at every single space, so the two spaces leave an empty string between them: ['a', '', 'b']. split() with no argument treats any run of whitespace as one separator: ['a', 'b'].
split(" ") 在每一个空格处切开,两个空格之间留下一个空字符串:['a', '', 'b']。不带参数的 split() 把任意一串空白当作一个分隔符:['a', 'b']。
Write two different expressions that turn "pYTHON" into "Python".写出两个不同的表达式,把 "pYTHON" 变成 "Python"。
"pYTHON".capitalize() returns "Python" (first letter upper, the rest lower). Equivalent by hand: s[0].upper() + s[1:].lower() with s = "pYTHON" gives "P" + "ython".
"pYTHON".capitalize() 返回 "Python"(首字母大写,其余小写)。手动写法等价:令 s = "pYTHON",s[0].upper() + s[1:].lower() 得到 "P" + "ython"。
After s = "cat" and the line s.upper() on its own, what does print(s) show, and how do you keep the uppercase version?在 s = "cat" 之后单独执行一行 s.upper(),print(s) 会显示什么?怎样保留大写版本?
It prints cat, because upper() returns a new string and the result was thrown away. Keep it with s = s.upper(), which makes s equal to "CAT".
会打印 cat,因为 upper() 返回新字符串,而结果被丢弃了。用 s = s.upper() 保留它,这样 s 就是 "CAT"。
Concatenation and String Formatting字符串拼接与格式化
- Join strings with
+, repeat them with*, and convert numbers withstr()before joining. - Convert text to numbers with
int()andfloat(), and explain theValueErrorraised byint("12.5")orint("abc"). - Build output with an f-string, including an expression and a format specification such as
:.2f,:<8or:>5. - Compare the
+, f-string and.format()approaches and say which is easiest to read.
- 用
+连接字符串、用*重复字符串,并在连接前用str()转换数字。 - 用
int()和float()把文本转换成数字,并解释int("12.5")或int("abc")引发的ValueError。 - 用 f-string 生成输出,包括表达式和格式说明,例如
:.2f、:<8或:>5。 - 比较
+、f-string 和.format()三种方式,并说明哪种最易读。
+operator (concatenation)+运算符(拼接):"Hello" + " " + "World"→"Hello World". Only works with strings; usestr(n)to convert numbers first.:"Hello" + " " + "World"→"Hello World"。只能用于字符串;先用str(n)将数字转换。- f-string (formatted string literal)f-string(格式化字符串字面量):
f"Score: {score}". The expression inside{}is evaluated and inserted. Readable and preferred in modern Python.:f"Score: {score}"。{}内的表达式被求值并插入。现代 Python 中首选,可读性强。 str.format()str.format():"Score: {}".format(score). Older style, still common in legacy code.:"Score: {}".format(score)。旧式写法,在旧代码中仍常见。
Worked Example 7: Building a grade report line例题 7:生成成绩报告行
Given a student name, subject, and score, produce a formatted report line three different ways.给定学生姓名、科目和分数,用三种不同方式生成格式化的报告行。
name = "Alice"
subject = "Biology"
score = 92
# Method 1: + concatenation
line1 = name + " | " + subject + " | " + str(score)
# Method 2: f-string
line2 = f"{name} | {subject} | {score}"
# Method 3: .format()
line3 = "{} | {} | {}".format(name, subject, score)
print(line1) # Alice | Biology | 92
print(line2) # Alice | Biology | 92
print(line3) # Alice | Biology | 92
以上三种方式输出相同。+ 需要 str(score) 转换;f-string(格式化字符串)最简洁,现代 Python 推荐。注意字符串是不可变的(immutable),每次操作都返回新字符串。All three produce the same output. The + method requires explicit str(score) conversion; f-strings handle it automatically and are the modern Python recommendation. Note: every operation returns a new string, because strings are immutable.
Worked Example 8: Parsing text into numbers and formatting a report例题 8:把文本解析成数字并格式化报告
The text "85,90,78" holds three scores. Parse it into integers, compute the average, print it to one decimal place, line up a name and a score in fixed-width columns, and show why "12" + "30" is not 42.文本 "85,90,78" 含有三个分数。把它解析成整数,计算平均值并保留一位小数输出,用固定宽度的列对齐姓名和分数,并说明为什么 "12" + "30" 不等于 42。
raw = "85,90,78"
scores = [int(part) for part in raw.split(",")]
print(scores) # [85, 90, 78]
average = sum(scores) / len(scores)
print(average) # 84.33333333333333
print(f"Average: {average:.1f}") # Average: 84.3
print(f"{'Ana':<8}|{92:>5}|") # Ana | 92|
print(int("12") + int("30")) # 42
print("12" + "30") # 1230
print(int(float("12.5"))) # 12
# int("12.5") raises ValueError: invalid literal for int() with base 10: '12.5'
split(",") parses the text into the pieces "85", "90" and "78", and int() converts each piece to a number. The sum is 253 and 253 / 3 is 84.333..., so :.1f rounds the display to 84.3 without changing the stored value. In {'Ana':<8} the < left-aligns in a field 8 characters wide; in {92:>5} the > right-aligns in 5 characters. The + operator joins two strings, so "12" + "30" is "1230" while int("12") + int("30") adds numbers to get 42. int() accepts only whole-number text: for "12.5" convert with float() first, then int() truncates to 12.split(",") 把文本解析成 "85"、"90"、"78" 三段,int() 再把每段转换为数字。总和为 253,253 / 3 = 84.333...,所以 :.1f 只是把显示四舍五入为 84.3,并不改变存储的值。在 {'Ana':<8} 中,< 表示在 8 个字符宽的字段内左对齐;在 {92:>5} 中,> 表示在 5 个字符宽的字段内右对齐。+ 运算符连接两个字符串,所以 "12" + "30" 是 "1230",而 int("12") + int("30") 是数字相加,得到 42。int() 只接受整数形式的文本:对 "12.5" 要先用 float() 转换,再由 int() 截断为 12。
"Score: " + str(85) return?"Score: " + str(85) 返回什么?str(85) converts the integer 85 to the string "85", then + concatenates it with "Score: " to give "Score: 85".str(85) 将整数 85 转换为字符串 "85",然后 + 将其与 "Score: " 拼接,得到 "Score: 85"。str() the + between a string and int raises TypeError. With str(85) the conversion succeeds and produces "Score: 85".没有 str(),字符串和整数之间的 + 会引发 TypeError。有 str(85) 则转换成功,产生 "Score: 85"。x = 7, what does f"Value is {x * 2}" return?给定 x = 7,f"Value is {x * 2}" 返回什么?{} is evaluated at runtime. x * 2 = 7 * 2 = 14, so the result is the string "Value is 14".在 f-string 中,{} 内的表达式在运行时被求值。x * 2 = 7 * 2 = 14,因此结果是字符串 "Value is 14"。{}, they do not insert the literal text. x * 2 evaluates to 14, giving "Value is 14".f-string 对 {} 中的表达式求值,不是插入字面文本。x * 2 求值为 14,得到 "Value is 14"。Questions that say write, convert or format check that the types match. Common errors: "Score: " + 92 (a TypeError; use str(92) or an f-string), forgetting that input() returns text so "5" + "3" is "53" and not 8, trying int("12.5") or int("") (a ValueError), and leaving off the f in front of the quotes so the braces print as text.
遇到write(编写)、convert(转换)或 format(格式化)类题目,要检查类型是否匹配。常见错误:"Score: " + 92(TypeError,应使用 str(92) 或 f-string);忘记 input() 返回的是文本,因此 "5" + "3" 是 "53" 而不是 8;尝试 int("12.5") 或 int("")(ValueError);以及在引号前漏写 f,导致花括号被当作普通文本输出。
What do "5" + "3", int("5") + int("3") and "5" * 3 evaluate to?"5" + "3"、int("5") + int("3") 和 "5" * 3 的值分别是什么?
"5" + "3" joins text and gives "53"; int("5") + int("3") adds numbers and gives 8; "5" * 3 repeats the text and gives "555".
"5" + "3" 连接文本,得到 "53";int("5") + int("3") 是数字相加,得到 8;"5" * 3 重复文本,得到 "555"。
Evaluate f"{3.14159:.2f}" and f"{7:03d}".计算 f"{3.14159:.2f}" 和 f"{7:03d}"。
:.2f shows two decimal places, so the first is "3.14". :03d pads an integer with zeros to width 3, so the second is "007".
:.2f 显示两位小数,所以第一个是 "3.14"。:03d 把整数用 0 补足到宽度 3,所以第二个是 "007"。
Why does int("12.5") fail, and what converts "12.5" to the whole number 12?为什么 int("12.5") 会失败?什么方法能把 "12.5" 转成整数 12?
int() accepts only text that looks like a whole number, so "12.5" raises a ValueError. Convert in two steps: int(float("12.5")), where float gives 12.5 and int truncates it to 12.
int() 只接受形如整数的文本,所以 "12.5" 会引发 ValueError。分两步转换:int(float("12.5")),其中 float 得到 12.5,int 截断为 12。
Searching Within Strings在字符串中搜索
- Test membership with
in, locate a substring withfindandindex, and count occurrences withcount. - Explain that
findreturns-1when the text is absent whileindexraises aValueError. - Compare strings with
==,<and>, and explain the result using Unicode code points (ordandchr), for example why"Z" < "a"is true. - Sort strings in default order and in case-insensitive order with
key=str.lower.
- 用
in测试成员关系,用find和index定位子串,用count统计出现次数。 - 解释
find在找不到时返回-1,而index会引发ValueError。 - 用
==、<和>比较字符串,并用 Unicode 码点(ord和chr)解释结果,例如为什么"Z" < "a"为真。 - 用默认顺序和
key=str.lower的不区分大小写顺序对字符串排序。
sub in s: returnsTrueorFalse. Simplest way to check membership."cat" in "concatenate"→True.:返回True或False。检查成员关系最简单的方式。"cat" in "concatenate"→True。s.find(sub): returns the index of the first occurrence, or-1if not found."hello".find("ll")→2.:返回第一次出现的索引,未找到则返回-1。"hello".find("ll")→2。s.count(sub): returns the number of non-overlapping occurrences."banana".count("a")→3.:返回不重叠出现次数。"banana".count("a")→3。
s.count(). AP CSP Topic 3.4 (Strings) and Skill 4.B ("Determine the result of code segments") ask you to predict string-operation results by hand.课程依据:ON ICS3C A1.2(原文):"计算单词或字母的出现次数",那就是 s.count()。AP CSP 主题 3.4(字符串)和技能 4.B(确定代码段的结果)要求你手动预测字符串操作的结果。
Worked Example 9: Analysing a sentence例题 9:分析一个句子
Use all three search tools on the sentence "the quick brown fox".在句子 "the quick brown fox" 上使用全部三种搜索工具。
sentence = "the quick brown fox"
# in: membership test
print("fox" in sentence) # True
print("cat" in sentence) # False
# find: first index (-1 if absent)
print(sentence.find("quick")) # 4
print(sentence.find("cat")) # -1
# count: occurrences
print(sentence.count("o")) # 2 (brown, fox)
print(sentence.count("the")) # 1
以上:in 返回布尔值(True/False),find() 返回第一个匹配的索引(方法,method),count() 计算不重叠的出现次数。"brown" 中的 o 和 "fox" 中的 o 各算一次,共 2 次。in returns bool. find() returns the start index of the first match (or -1). count() counts non-overlapping occurrences: "o" appears in "brown" (index 12) and "fox" (index 17), so the total is 2.
Comparing strings比较字符串
A comparison such as ==, < or > between two strings is a non-numeric comparison: Python looks at the first position where the strings differ and compares the two characters by their Unicode code point, the whole number that ord() returns. Because computers store text as numbers, the digits "0" to "9" are 48 to 57, the capitals "A" to "Z" are 65 to 90, and the lowercase letters "a" to "z" are 97 to 122. If one string is a prefix of the other, the shorter string is smaller.两个字符串之间的 ==、<、> 比较是非数值比较:Python 找到两者第一个不同的位置,按 Unicode 码点(ord() 返回的整数)比较这两个字符。因为计算机把文本存成数字,数字 "0" 到 "9" 对应 48 到 57,大写字母 "A" 到 "Z" 对应 65 到 90,小写字母 "a" 到 "z" 对应 97 到 122。如果一个字符串是另一个的前缀,较短的更小。
print(ord("A"), ord("Z"), ord("a"), ord("0"), ord("9")) # 65 90 97 48 57
Common errors: expecting "apple" < "Apple" to be true (it is false, because "a" is 97 and "A" is 65), and comparing numbers stored as text ("10" < "9" is true because "1" is 49 and "9" is 57; convert with int() first to compare values).常见错误:以为 "apple" < "Apple" 为真(实际为假,因为 "a" 是 97 而 "A" 是 65);以及比较以文本形式存储的数字("10" < "9" 为真,因为 "1" 是 49、"9" 是 57;要比较数值请先用 int() 转换)。
find or index?find 还是 index?
Both return the position of the first match. The difference is what happens when the text is missing: find returns -1, while index raises a ValueError. Use find when absence is normal and you will test the result, and index when absence would be a bug. A second argument tells find where to start looking, which is how you find the next match.两者都返回第一个匹配的位置。区别在于找不到时:find 返回 -1,而 index 会引发 ValueError。找不到属于正常情况、并且你会检查结果时用 find;找不到就意味着程序有错时用 index。第二个参数告诉 find 从哪里开始查找,这就是查找下一个匹配的方法。
text = "hello"
print(text.find("l")) # 2
print(text.find("z")) # -1
print(text.index("l")) # 2
print(text.find("l", 3)) # 3
# text.index("z") raises ValueError: substring not found
Worked Example 10: Comparing and sorting strings例题 10:比较与排序字符串
Predict each comparison, explain the two surprising ones ("Z" before "a", and "10" before "9"), then sort a list of words in default order and in case-insensitive order.预测每个比较的结果,解释两个出人意料的结果("Z" 在 "a" 之前,以及 "10" 在 "9" 之前),然后分别按默认顺序和不区分大小写的顺序给单词列表排序。
print("apple" < "banana") # True
print("Z" < "a") # True
print("apple" < "Apple") # False
print("10" < "9") # True
print(10 < 9) # False
print("abc" < "abcd") # True
print(ord("Z"), ord("a")) # 90 97
print(chr(ord("a") + 1)) # b
words = ["pear", "Zebra", "apple", "Mango"]
print(sorted(words)) # ['Mango', 'Zebra', 'apple', 'pear']
print(sorted(words, key=str.lower)) # ['apple', 'Mango', 'pear', 'Zebra']
The first position where the strings differ decides. "a" (97) is before "b" (98), so "apple" < "banana" is true. "Z" is 90 and "a" is 97, so "Z" < "a" is true even though z is late in the alphabet. In "apple" < "Apple" the first characters are "a" (97) and "A" (65), so the result is false. "10" < "9" compares "1" (49) with "9" (57), which is true for text, whereas for the numbers 10 and 9 the comparison 10 < 9 is false. "abc" is a prefix of "abcd", so it is smaller. chr(ord("a") + 1) steps one code point forward to "b". Default sorted puts every capital before every lowercase letter; key=str.lower compares lowercase copies but keeps the original spelling in the result.第一个不同的位置决定结果。"a"(97)在 "b"(98)之前,所以 "apple" < "banana" 为真。"Z" 是 90,"a" 是 97,所以即使 z 在字母表中靠后,"Z" < "a" 也为真。在 "apple" < "Apple" 中,第一个字符是 "a"(97)和 "A"(65),结果为假。"10" < "9" 比较的是 "1"(49)和 "9"(57),对文本而言为真,而对数字 10 和 9 来说,10 < 9 为假。"abc" 是 "abcd" 的前缀,所以更小。chr(ord("a") + 1) 把码点向前移一位,得到 "b"。默认的 sorted 把所有大写字母排在所有小写字母之前;key=str.lower 比较的是小写副本,但结果保留原来的拼写。
"banana".count("an") return?"banana".count("an") 返回什么?count() counts non-overlapping matches, so the answer is 2."an" 在 "banana" 中出现两次:位置 1 和 3。count() 计算不重叠匹配,因此答案是 2。"hello".find("x") return?"hello".find("x") 返回什么?find() returns -1 when the substring is not found. "x" is not in "hello", so the result is -1.find() 在未找到子字符串时返回 -1。"x" 不在 "hello" 中,因此结果是 -1。find() returns an integer: the index if found, or -1 if not found. It never returns False or None. Use in for a boolean membership test.find() 返回整数:找到则返回索引,未找到则返回 -1。它不会返回 False 或 None。用 in 进行布尔成员测试。For predict and explain questions on searching, state the return type first: in gives a bool, find gives an index or -1, count gives an integer. Common errors: writing if s.find(x): as a membership test (the value -1 is true, and a match at index 0 is false), searching for "h" in "Hello" and forgetting that matching is case-sensitive, and assuming count includes overlapping matches ("aaa".count("aa") is 1).
遇到搜索类的predict(预测)和explain(解释)题目,先写出返回类型:in 给出布尔值,find 给出索引或 -1,count 给出整数。常见错误:把 if s.find(x): 当作成员测试(值 -1 为真,而在索引 0 处匹配反而为假);在 "Hello" 中搜索 "h" 却忘了匹配区分大小写;以为 count 会计入重叠匹配("aaa".count("aa") 是 1)。
Evaluate "Zoo" < "apple" and "zoo" < "apple", and explain both results.计算 "Zoo" < "apple" 和 "zoo" < "apple",并解释两个结果。
The first is true: "Z" is 90 and "a" is 97. The second is false: "z" is 122, which is greater than "a" (97). Only the case of the first letter differs, yet the order changes.
第一个为真:"Z" 是 90,"a" 是 97。第二个为假:"z" 是 122,大于 "a"(97)。只有首字母的大小写不同,顺序却变了。
For s = "mississippi", give s.count("ss"), s.find("ss") and s.find("ss", 3).对 s = "mississippi",给出 s.count("ss")、s.find("ss") 和 s.find("ss", 3)。
The letters m=0, i=1, s=2, s=3, i=4, s=5, s=6, i=7, p=8, p=9, i=10 show "ss" at indices 2 and 5. So count gives 2, find("ss") gives 2, and find("ss", 3) starts looking at index 3, so it finds the next one at 5.
字母 m=0, i=1, s=2, s=3, i=4, s=5, s=6, i=7, p=8, p=9, i=10,说明 "ss" 出现在索引 2 和 5。所以 count 得到 2,find("ss") 得到 2,而 find("ss", 3) 从索引 3 开始找,因此找到的是下一个,索引 5。
A student tests whether "x" is in s with if s.find("x"):. Give one string where this gives the wrong answer in each direction and write the correct test.一名学生用 if s.find("x"): 测试 "x" 是否在 s 中。给出两个字符串,分别使这个测试在两个方向上出错,并写出正确的测试。
For s = "abc" the call returns -1, which is true, so the test wrongly says "x" is present. For s = "xyz" the call returns 0, which is false, so it wrongly says "x" is absent. The correct test is if "x" in s: (or s.find("x") != -1).
当 s = "abc" 时调用返回 -1,其值为真,所以测试错误地认为 "x" 存在。当 s = "xyz" 时调用返回 0,其值为假,所以错误地认为 "x" 不存在。正确的测试是 if "x" in s:(或 s.find("x") != -1)。
Why does sorted(["pear", "Zebra", "apple", "Mango"]) put "Zebra" before "apple", and how do you get a case-insensitive order?为什么 sorted(["pear", "Zebra", "apple", "Mango"]) 把 "Zebra" 排在 "apple" 之前?怎样得到不区分大小写的顺序?
Capitals have smaller code points (65 to 90) than lowercase letters (97 to 122), so the default order is ["Mango", "Zebra", "apple", "pear"]. Add key=str.lower to compare lowercase copies and get ["apple", "Mango", "pear", "Zebra"].
大写字母的码点(65 到 90)小于小写字母(97 到 122),所以默认顺序是 ["Mango", "Zebra", "apple", "pear"]。加上 key=str.lower 比较小写副本,得到 ["apple", "Mango", "pear", "Zebra"]。
Looping Over Characters遍历字符
- Choose between
for ch in sandfor i in range(len(s)), and name a task that needs each. - Write an accumulator loop that counts the characters meeting a condition, such as vowels or capitals.
- Build a new string one character at a time, trace it, and explain why
+=in a long loop is a poor choice. - Compare characters from both ends of a string to test a palindrome.
- 在
for ch in s与for i in range(len(s))之间做出选择,并说出各自适用的任务。 - 编写累加器循环,统计满足条件的字符个数,例如元音或大写字母。
- 逐个字符构建新字符串并追踪其过程,解释为什么在长循环中使用
+=不是好选择。 - 从字符串两端向中间比较字符,检测回文。
- For-each (direct)for-each(直接遍历)
for ch in s::chtakes each character in turn. Cleaner when you only need the character, not its index.:ch依次取每个字符。当只需要字符而不需要索引时更简洁。 - For-range (index access)for-range(索引访问)
for i in range(len(s)):: uses[i]inside the loop. Needed when you must know the position.:在循环内用s[i]。当必须知道位置时使用。
Worked Example 11: Counting vowels in a word例题 11:统计单词中的元音字母
Count how many vowels are in the word "education" using both loop styles.用两种循环方式统计单词 "education" 中的元音字母数量。
word = "education"
vowels = "aeiou"
# Style 1: for-each (cleaner)
count1 = 0
for ch in word:
if ch in vowels:
count1 += 1
print(count1) # 5
# Style 2: for-range (index-based)
count2 = 0
for i in range(len(word)):
if word[i] in vowels:
count2 += 1
print(count2) # 5
以上:Style 1 用 for ch in word 逐字符(character)遍历;Style 2 用索引(index)访问。"education" 中的元音:e, u, a, i, o,共 5 个。两种方式结果相同。Both styles produce the same result. "education": e(vowel), d, u(vowel), c, a(vowel), t, i(vowel), o(vowel), n, 5 vowels. Style 1 is more Pythonic; Style 2 is needed when the position matters (e.g., to replace word[i]).
+= inside a loop常见错误:在循环中用 += 重建字符串
The reversal quiz below uses result = ch + result inside a loop, and it is tempting to reach for the same pattern any time you build a string character by character: start with result = "", then result += ch on every pass. Because strings are immutable (§1), each += does not append to result in place; it allocates an entirely new string and copies the old contents into it. For a short word this is invisible, but for a long document processed one character at a time, the total copying work grows roughly with the square of the length, not with the length itself.下面的反转测验在循环中使用了 result = ch + result,而每当你想逐字符构建字符串时,很容易套用同样的写法:先 result = "",再每次循环 result += ch。由于字符串是不可变的(见 §1),每一次 += 并不会就地追加到 result;它会分配一个全新的字符串,并把旧内容复制进去。对短单词来说这毫无影响,但对逐字符处理的长文档来说,总复制开销大致随长度的平方增长,而不是随长度线性增长。
The fix mirrors Worked Example 6: collect the pieces in a list with append(), then call "".join(pieces) once at the end. The list grows in roughly constant time per append, and join() makes a single linear pass over the whole collection, so the total cost stays proportional to the length of the text. Prefer this pattern for any real text-processing pipeline, including the word-count program in §7.修复方式与例题 6 相呼应:先用 append() 把各片段收集到一个列表中,最后只调用一次 "".join(pieces)。列表的每次追加大致是常数时间,join() 只对整个集合做一次线性遍历,因此总开销与文本长度成正比。在任何真正的文本处理流水线中都应优先采用这种模式,包括 §7 的词频统计程序。
Worked Example 12: Palindrome Check, Combining Slicing and Looping例题 12:回文检测,结合切片与循环
A palindrome reads the same forwards and backwards, such as "level" or "racecar". Write two solutions to the same problem: a one-line slicing solution built from §2, and a manual loop solution that compares characters from both ends inward, stopping in one pass as soon as a mismatch appears.回文正读反读都相同,例如 "level" 或 "racecar"。为同一问题写两种解法:一种是基于 §2 的一行切片解法,另一种是从两端向中间比较字符的手动循环解法,一旦发现不匹配便在一次遍历中提前停止。
def is_palindrome_slice(s):
return s == s[::-1]
def is_palindrome_loop(s):
left = 0
right = len(s) - 1
while left < right:
if s[left] != s[right]:
return False
left += 1
right -= 1
return True
print(is_palindrome_slice("racecar")) # True
print(is_palindrome_loop("racecar")) # True
print(is_palindrome_slice("hello")) # False
print(is_palindrome_loop("hello")) # False
以上:is_palindrome_slice 用 §2 的反转切片 s[::-1],把整个字符串复制一份再比较,写法简洁但要建出第二个字符串。is_palindrome_loop 用两个索引(§1 的索引访问)从两端向中间靠拢,一旦 s[left] != s[right] 就立刻用 return False 退出,最坏情况下也只需比较约一半字符,且不需要建出反转副本。两种写法结果相同,但循环写法把索引、比较和提前退出结合在同一次遍历中,是组合多种字符串技巧的典型例子。is_palindrome_slice reuses the reversal slice s[::-1] from §2: concise, but it builds an entirely new reversed string just to compare it. is_palindrome_loop uses two indices (index access from §1) that walk inward from both ends, returning False the moment a mismatch is found; in the worst case it only compares roughly half the characters and never allocates a second string. Both return the same answer, but the loop version combines indexing, comparison, and early exit in a single pass, the pattern to reach for once slicing and looping are both in your toolkit.
s = "hello"result = ""for ch in s:result = ch + resultprint(result)以下代码打印什么?s = "hello"result = ""for ch in s:result = ch + resultprint(result)result. Trace: ""→"h"→"eh"→"leh"→"lleh"→"olleh". The loop reverses the string.每个字符被前置(放在)result 之前。追踪:""→"h"→"eh"→"leh"→"lleh"→"olleh"。该循环反转了字符串。result = ch + result, which places the new character before the accumulated string. After all 5 characters, the string is reversed: "olleh".每次迭代执行 result = ch + result,将新字符放在累积字符串之前。经过所有 5 个字符后,字符串被反转:"olleh"。for i in range(len(s)) gives both the index i and the character s[i], so you know where each character is. Use this when position matters (e.g., swapping characters, building a new string with changes at specific positions).for i in range(len(s)) 同时给出索引 i 和字符 s[i],因此你知道每个字符的位置。当位置重要时使用此方式(例如,交换字符、在特定位置构建带更改的新字符串)。for ch in s gives the character but not its index. When you need the position, use for i in range(len(s)) and access the character as s[i].for ch in s 给出字符但不给出其索引。当你需要位置时,使用 for i in range(len(s)) 并以 s[i] 访问字符。For trace and write a loop questions, draw a small table with one column for i (if used), one for ch and one for the accumulator, and fill one row per pass. Common errors: starting the counter inside the loop so it resets each time, writing count = 1 where count += 1 is needed, using range(len(s) - 1) and skipping the last character, and expecting a loop to change the original string (it only reads it).
遇到trace(追踪)和write a loop(编写循环)类题目,画一个小表:一列放 i(如果用到),一列放 ch,一列放累加器,每执行一轮填一行。常见错误:把计数器的初始化写在循环里,导致每轮都被重置;在需要 count += 1 的地方写成 count = 1;使用 range(len(s) - 1) 而漏掉最后一个字符;以为循环会改变原字符串(它只是读取)。
What does this print? s = "abc", then for i in range(len(s)): print(i, s[i]).下面的代码打印什么?s = "abc",然后 for i in range(len(s)): print(i, s[i])。
It prints three lines: 0 a, 1 b and 2 c. The loop variable i takes the values 0, 1, 2 (the valid indices) and s[i] is the character at each.
打印三行:0 a、1 b 和 2 c。循环变量 i 依次取 0、1、2(有效索引),s[i] 是对应位置的字符。
Write a loop that counts the capital letters in "Hello World" and state the result.编写循环,统计 "Hello World" 中大写字母的个数,并给出结果。
n = 0, then for ch in "Hello World": with if ch.isupper(): n += 1 inside. The capitals are "H" and "W", so n is 2.
n = 0,然后 for ch in "Hello World":,循环内写 if ch.isupper(): n += 1。大写字母是 "H" 和 "W",所以 n 为 2。
Trace result = "" followed by for ch in "abc": result = result + ch.upper() + "-". What is result at the end?追踪 result = "" 以及 for ch in "abc": result = result + ch.upper() + "-"。最后 result 是什么?
Pass 1 gives "A-", pass 2 gives "A-B-", pass 3 gives "A-B-C-". The final value is "A-B-C-", with a trailing hyphen because the hyphen is added on every pass.
第 1 轮得到 "A-",第 2 轮得到 "A-B-",第 3 轮得到 "A-B-C-"。最终值为 "A-B-C-",末尾带一个连字符,因为每一轮都会添加连字符。
Text-Processing Worked Example: Word Count文本处理综合例题:词频统计
- Build a word-count pipeline: normalise with
lower()andstrip(), split into words, then count with a dictionary. - Explain why
split()andsplit(" ")differ when the text has repeated spaces. - Strip punctuation from the ends of each token so that "be," and "be" count as one word.
- Report the most frequent word and explain how ties are handled.
- 构建词频统计流水线:用
lower()和strip()规范化,拆分成单词,再用字典计数。 - 解释当文本含有连续空格时,
split()与split(" ")为什么不同。 - 去掉每个词元两端的标点,使 "be," 和 "be" 被算作同一个词。
- 报告出现次数最多的词,并说明并列时如何处理。
- Step 1: Normalise第 1 步:规范化:
lower()+strip()so "The" and "the" count as the same word.:lower()+strip()使"The"和"the"被计为同一个词。 - Step 2: Split第 2 步:分割:
split()with no argument splits on any whitespace, collapsing multiple spaces.:无参数的split()按任意空白分割,合并多个空格。 - Step 3: Count第 3 步:计数: loop over the word list and count occurrences, or use a dictionary for frequency per word.:遍历词列表并计数,或用字典统计每个词的频率。
Worked Example 13: Word-count program例题 13:词频统计程序
Given a sentence, count the total number of words, find the most frequent word, and report whether a target word appears.给定一个句子,统计总词数,找出出现最多的词,并报告目标词是否出现。
sentence = "the cat sat on the mat and the cat"
# Step 1: Normalise
text = sentence.lower().strip()
# Step 2: Split into words
words = text.split() # ['the', 'cat', 'sat', 'on', 'the', 'mat', 'and', 'the', 'cat']
# Step 3: Count total words
total = len(words)
print(f"Total words: {total}") # Total words: 9
# Step 4: Frequency of each unique word
freq = {}
for w in words:
if w in freq:
freq[w] += 1
else:
freq[w] = 1
print(freq)
# {'the': 3, 'cat': 2, 'sat': 1, 'on': 1, 'mat': 1, 'and': 1}
# Step 5: Most frequent word
top = max(freq, key=freq.get)
print(f"Most frequent: '{top}' ({freq[top]} times)")
# Most frequent: 'the' (3 times)
# Step 6: Target search
target = "cat"
print(f"'{target}' appears: {'yes' if target in words else 'no'}")
# 'cat' appears: yes
以上流水线:lower() 规范化,split() 分割为词列表,len() 计总词数,字典统计词频(频率),max() 找最高频词,in 检查目标词是否存在。这综合了本单元所有字符串技能。Pipeline: lower() normalises case, split() tokenises (splits into word list), len() counts total words, the dict loop counts frequency per word, max() finds the top word, and in tests membership. This integrates all six earlier sections.
Worked Example 14: Word count with punctuation and ties例题 14:含标点和并列情况的词频统计
Count the words in "To be, or not to be: that is the question. To be!" after removing the punctuation that sticks to the words, then list the three highest counts so that ties are ordered alphabetically. Also show how split() and split(" ") treat a double space.去掉粘在单词上的标点后,统计 "To be, or not to be: that is the question. To be!" 中的词频,然后列出最高的三个计数,并列时按字母顺序排列。同时展示 split() 与 split(" ") 对双空格的处理。
text = "To be, or not to be: that is the question. To be!"
tokens = text.lower().split()
print(tokens)
# ['to', 'be,', 'or', 'not', 'to', 'be:', 'that', 'is', 'the', 'question.', 'to', 'be!']
words = [t.strip(".,;:!?") for t in tokens]
print(words)
# ['to', 'be', 'or', 'not', 'to', 'be', 'that', 'is', 'the', 'question', 'to', 'be']
freq = {}
for w in words:
freq[w] = freq.get(w, 0) + 1
print(freq)
# {'to': 3, 'be': 3, 'or': 1, 'not': 1, 'that': 1, 'is': 1, 'the': 1, 'question': 1}
ranked = sorted(freq.items(), key=lambda pair: (-pair[1], pair[0]))
print(ranked[:3]) # [('be', 3), ('to', 3), ('is', 1)]
print("a b".split(" ")) # ['a', '', 'b']
print("a b".split()) # ['a', 'b']
Lowercasing and split() give 12 tokens, but some still carry punctuation: "be,", "be:", "question." and "be!". strip(".,;:!?") removes those characters from the ends of each token only, so "be," becomes "be" and the dictionary counts "to" 3 times and "be" 3 times. The sort key (-pair[1], pair[0]) orders by count from high to low, and by word from A to Z when counts tie, so "be" comes before "to". max(freq, key=freq.get) would return "to", the first of the tied words inserted, which depends on input order. Finally, split(" ") returns an empty string for the double space, so the count of words would be wrong; plain split() treats the whole run of spaces as one separator.转为小写并用 split() 拆分后得到 12 个词元,但有些仍带标点:"be,"、"be:"、"question." 和 "be!"。strip(".,;:!?") 只去掉每个词元两端的这些字符,所以 "be," 变成 "be",字典中 "to" 计 3 次,"be" 也计 3 次。排序键 (-pair[1], pair[0]) 先按计数从高到低排序,计数相同时按单词从 A 到 Z 排序,所以 "be" 排在 "to" 前面。max(freq, key=freq.get) 会返回 "to",即并列者中最先插入的那个,取决于输入顺序。最后,split(" ") 遇到双空格会产生空字符串,导致词数出错;不带参数的 split() 把整串空格当作一个分隔符。
text = "To be or not to be", what does text.lower().split() return?给定 text = "To be or not to be",text.lower().split() 返回什么?lower() first converts to all lowercase → "to be or not to be". Then split() splits on whitespace into a list: ["to","be","or","not","to","be"].lower() 先转为全小写 → "to be or not to be"。再 split() 按空白分割成列表:["to","be","or","not","to","be"]。.lower().split() applies both operations in sequence. Result is a list of lowercase words.链式调用 .lower().split() 按顺序应用两个操作。结果是小写词的列表。"the cat sat on the mat and the cat", what is the total number of words?对 "the cat sat on the mat and the cat" 运行词频统计程序后,总词数是多少?len(words) = 9.按空格分割:"the","cat","sat","on","the","mat","and","the","cat",9 个词元。len(words) = 9。Going deeper, removing punctuation before word-count Honors, ICS3C / CSE1120深入,计数前去除标点 荣誉,ICS3C / CSE1120
Real text contains commas, periods, and quotation marks, so "word," and "word" count as different tokens. The standard fix is to strip punctuation from each token before inserting it into the frequency dictionary. One approach: word.strip('.,!?;:"'). A more general solution uses the str.translate() method with str.maketrans() to remove all punctuation at once. ON ICS3C A1.2 names "extract a portion" and "count occurrences" as the assessed skills; handling punctuation cleanly is the distinction between a basic and a polished solution.真实文本包含逗号、句号和引号,因此 "word," 和 "word" 会被计为不同的词元。标准修复是在将每个词元插入频率字典之前去除标点。一种方法:word.strip('.,!?;:"')。更通用的解决方案使用 str.translate() 方法配合 str.maketrans() 一次去除所有标点。ON ICS3C A1.2 将"提取一部分"和"计算出现次数"列为评估技能;干净地处理标点是基础解法和精良解法之间的区别。
For a write a program question, name the stages in order (normalise, split, clean, count, report) and write a comment for each. Common errors: counting before calling lower() so "To" and "to" are different keys, leaving punctuation attached to words, splitting on a single space when the text can contain repeated spaces, and printing a dictionary when the question asks for the most frequent word. If two words tie, say how you chose between them.
遇到write a program(编写程序)类题目,按顺序写出各阶段(规范化、拆分、清理、计数、报告),并为每个阶段写一条注释。常见错误:在调用 lower() 之前计数,使 "To" 和 "to" 成为不同的键;让标点粘在单词上;在文本可能含连续空格时按单个空格拆分;题目要求最高频的词却打印了整个字典。如果两个词并列,要说明你如何在它们之间选择。
For "To be or not to be", how many words does split() give after lower(), and how many different words are there?对 "To be or not to be",lower() 之后 split() 得到多少个词?共有多少个不同的词?
The list is ['to', 'be', 'or', 'not', 'to', 'be'], so there are 6 words. The different words are "to", "be", "or" and "not", so there are 4.
列表是 ['to', 'be', 'or', 'not', 'to', 'be'],所以有 6 个词。不同的词是 "to"、"be"、"or" 和 "not",共 4 个。
Write the frequency dictionary for the words ["a", "b", "a"] using a loop.用循环为单词列表 ["a", "b", "a"] 写出频率字典。
freq = {}, then for w in words: freq[w] = freq.get(w, 0) + 1. The result is {'a': 2, 'b': 1}.
freq = {},然后 for w in words: freq[w] = freq.get(w, 0) + 1。结果是 {'a': 2, 'b': 1}。
A dictionary is {"to": 3, "be": 3}. What does max(freq, key=freq.get) return, and how can you make the answer independent of insertion order?字典为 {"to": 3, "be": 3}。max(freq, key=freq.get) 返回什么?怎样让答案不依赖插入顺序?
It returns "to": when counts tie, max keeps the first one it meets, and "to" was inserted first. To fix the choice, sort with sorted(freq.items(), key=lambda pair: (-pair[1], pair[0])), which puts "be" first because ties are broken alphabetically.
返回 "to":计数相同时 max 保留最先遇到的那个,而 "to" 是最先插入的。要固定选择,可用 sorted(freq.items(), key=lambda pair: (-pair[1], pair[0])) 排序,由于并列时按字母顺序,"be" 会排在最前面。
Exam Strategy and Common Pitfalls考试策略与常见陷阱
- Zero-based indexing.从零开始的索引。 The first character is always index 0, not 1. A frequent slip is writing
s[1]for the first character. Negative indices count from the right:s[-1]is always the last character.第一个字符始终是索引 0,不是 1。常见的失误是用s[1]表示第一个字符。负索引从右计数:s[-1]始终是最后一个字符。 - Stop is excluded in slices.切片中的 stop 不包含。
s[0:3]gives three characters (indices 0, 1, 2), NOT four. To get the first n characters, writes[:n].s[0:3]给出三个字符(索引 0、1、2),不是四个。要获取前 n 个字符,写s[:n]。
- Strings are immutable.字符串是不可变的。
s.upper()returns a new string, it does NOT changes. Always assign the result:s = s.upper(). Forgetting this is a very common method-question mistake.s.upper()返回新字符串,它不改变s。必须赋值:s = s.upper()。忘记这点是方法题中很常见的错误。 find()returns-1, notFalse.find()返回-1,不是False。 Useinfor a boolean test; usefind()when you need the position. Note: the AP CSP reference pseudocode numbers string positions from 1, while Python starts at 0, so adjust by one when you move between them.布尔测试用in;需要位置时用find()。注意:AP CSP 参考伪代码从 1 开始给字符串位置编号,而 Python 从 0 开始,两者之间转换时要调整一位。
- Know the evaluation order.明确求值顺序。 Method chains run left to right; nested calls run innermost first. For a chain like
"hello".upper().replace("L","X"): Step 1:"HELLO". Step 2:"HEXXO". Write each intermediate value so the working is complete.方法链从左到右求值,嵌套调用先算最内层。对于链式调用如"hello".upper().replace("L","X"):第 1 步:"HELLO"。第 2 步:"HEXXO"。写出每个中间值,使过程完整。 - Count characters, not words.计字符,不是词。 When predicting
s.count("x"), count every occurrence of the literal character, not the number of words. Overlapping substrings are NOT counted:"aaa".count("aa")= 1, not 2.预测s.count("x")时,计算字面字符的每次出现,不是词数。重叠子字符串不计:"aaa".count("aa")= 1,不是 2。
- Convert numbers before
+concatenation.在+拼接前转换数字。"Score: " + 92raises a TypeError. Usestr(92)or an f-string instead:f"Score: {92}"."Score: " + 92会引发 TypeError。改用str(92)或 f-string:f"Score: {92}"。
Flashcards闪卡
s[0] vs s[-1]?s[0] 和 s[-1] 分别是什么?s[0] = first character. s[-1] = last character. Indices start at 0; negative indices count from the right.s[0] = 第一个字符。s[-1] = 最后一个字符。索引从 0 开始;负索引从右计数。s[start:stop], includes start, excludes stop. s[:3] = first 3. s[2:] = from index 2 to end. s[::-1] = reversed.s[start:stop],包含 start,不含 stop。s[:3] = 前 3 个。s[2:] = 索引 2 到末尾。s[::-1] = 反转。s.upper() / s.lower()s.upper() / s.lower()s = s.lower().返回所有字母大写/小写的新字符串。原字符串不变(不可变)。需赋值才能使用:s = s.lower()。s.split(sep)s.split(sep)sep, returns a list. No argument = split on any whitespace. "a,b".split(",") → ["a","b"].在 sep 处分割字符串,返回列表。无参数 = 按任意空白分割。"a,b".split(",") → ["a","b"]。sep.join(iterable)sep.join(iterable)sep between each pair. "-".join(["a","b","c"]) → "a-b-c".split 的逆操作。将列表元素用 sep 连接成一个字符串。"-".join(["a","b","c"]) → "a-b-c"。s.replace(old, new)s.replace(old, new)old with new, returns a new string. "aa".replace("a","b") → "bb".将每个 old 替换为 new,返回新字符串。"aa".replace("a","b") → "bb"。f"text {expr}", the expression inside {} is evaluated and inserted. f"Score: {90+2}" → "Score: 92". Modern Python preferred.f"text {expr}",{} 内的表达式被求值并插入。f"Score: {90+2}" → "Score: 92"。现代 Python 推荐。sub in ssub in sTrue if sub is found anywhere in s, else False. Simple membership test. "cat" in "concatenate" → True.如果 sub 在 s 中出现则返回 True,否则 False。最简单的成员测试。"cat" in "concatenate" → True。s.find(sub)s.find(sub)-1 if not found. Never returns False or None.返回第一次出现的索引,未找到则返回 -1。不会返回 False 或 None。s.count(sub)s.count(sub)sub in s. "banana".count("a") → 3. ON ICS3C A1.2 "count occurrences."返回 sub 在 s 中不重叠的出现次数。"banana".count("a") → 3。ON ICS3C A1.2"计算出现次数"。for ch in s: gives character, no index. for i in range(len(s)): gives index and character via s[i]. Use range when position matters.for ch in s:给出字符,无索引。for i in range(len(s)):通过 s[i] 给出索引和字符。当位置重要时用 range。lower() normalise. 2. split() tokenise. 3. Loop and count with a dict. ON ICS3C A1.2 "count occurrences of a word."1. lower() 规范化。2. split() 分词。3. 用字典循环计数。ON ICS3C A1.2"计算单词出现次数"。s[0] = "X", raises TypeError. Every method returns a new string. To "modify" s, reassign: s = s.replace("a","b").不能执行 s[0] = "X",引发 TypeError。每个方法都返回新字符串。要"修改" s,需重新赋值:s = s.replace("a","b")。Practice Quiz综合测验
s = "Data", what is s[1]?给定 s = "Data",s[1] 是什么?s[1] = "a".从零开始索引:D=0, a=1, t=2, a=3。s[1] = "a"。"Science"[1:5] return?"Science"[1:5] 返回什么?[1:5] = indices 1,2,3,4 = "cien". Stop index 5 excluded."Science":S=0,c=1,i=2,e=3,n=4,c=5,e=6。[1:5] = 索引 1,2,3,4 = "cien"。stop 索引 5 不含。"hello world".split() return?"hello world".split() 返回什么?split() with no argument splits on whitespace, returning a list of words: ["hello", "world"].无参数的 split() 按空白分割,返回词列表:["hello", "world"]。split() returns a list of tokens, not individual characters and not a number.split() 返回词元列表,不是单个字符,也不是数字。name = "Alice", what does f"Hello {name}!" evaluate to?给定 name = "Alice",f"Hello {name}!" 的结果是什么?{name} is evaluated and replaced with the value of name = "Alice". Result: "Hello Alice!".在 f-string 中,{name} 被求值并替换为 name 的值 = "Alice"。结果:"Hello Alice!"。{} expressions at runtime. {name} becomes "Alice".f-string 在运行时对 {} 表达式求值。{name} 变为 "Alice"。"mississippi".count("ss") return?"mississippi".count("ss") 返回什么?count("ss") counts non-overlapping "ss" substrings. In "mississippi": positions 2 and 5 = 2 occurrences.count("ss") 计算不重叠的 "ss" 子字符串。在 "mississippi" 中:位置 2 和 5 = 2 次出现。"code" and print 2. What does it actually print?s = "code"count = 0for ch in s:if ch in "aeiou":count = 1print(count)以下代码本应统计 "code" 中的元音并打印 2。实际打印什么?s = "code"count = 0for ch in s:if ch in "aeiou":count = 1print(count)count = 1 instead of count += 1. Every time a vowel is found, count is reset to 1, not incremented. "code" has vowels "o" and "e"; the last one sets count = 1. Fix: count += 1.错误是 count = 1 而不是 count += 1。每次找到元音时,count 被重置为 1,而不是递增。"code" 有元音 "o" 和 "e";最后一个将 count 设为 1。修复:count += 1。count = 1 resets count to 1 on every vowel, it doesn't accumulate. The last vowel "e" sets count = 1, so print(count) outputs 1.count = 1 在每次遇到元音时将 count 重置为 1,不累积。最后一个元音 "e" 将 count 设为 1,因此 print(count) 输出 1。Readiness Checklist准备就绪清单
Tick each item when you can do it cold, without notes, on a first attempt.能在无笔记、首次尝试下完成,再勾选每一项。
- Given any string, state the character at a specific positive index and negative index without running code. Explain why indices start at 0. 🇺🇸 AP CSP 3.4 / 🇨🇦 AB CSE1110 2.4.3给定任意字符串,不运行代码说出特定正索引和负索引处的字符。解释为何索引从 0 开始。🇺🇸 AP CSP 3.4 / 🇨🇦 AB CSE1110 2.4.3
- Predict the output of any slice expression
s[start:stop]ors[start:stop:step]by applying the "stop is excluded" rule. 🇺🇸 AP CSP Skill 4.B / 🇨🇦 ON ICS3C A1.2通过应用"stop 不含"规则,预测任意切片表达式s[start:stop]或s[start:stop:step]的输出。🇺🇸 AP CSP 技能 4.B / 🇨🇦 ON ICS3C A1.2 - Use
upper(),lower(),split(),join(), andreplace()correctly and explain why assigning the return value is required. 🇨🇦 ON ICS3C A1.2 / AB CSE1120 2.6正确使用upper()、lower()、split()、join()和replace(),并解释为何需要赋值返回值。🇨🇦 ON ICS3C A1.2 / AB CSE1120 2.6 - Write a formatted output line using an f-string that embeds at least one variable and one computed expression. 🇨🇦 AB CSE1110 2.4.6 / AB CSE1120 2.6用 f-string 写出包含至少一个变量和一个计算表达式的格式化输出行。🇨🇦 AB CSE1110 2.4.6 / AB CSE1120 2.6
- Distinguish the return values of
in(bool),find()(int / -1), andcount()(int); predict each for a given string and target without running the code. 🇺🇸 AP CSP 3.4 / 🇨🇦 ON ICS3C A1.2区分in(布尔值)、find()(整数 / -1)和count()(整数)的返回值;对给定字符串和目标,不运行代码预测各自结果。🇺🇸 AP CSP 3.4 / 🇨🇦 ON ICS3C A1.2 - Write a for-each loop that counts vowels in a string from scratch, without using built-in methods. 🇨🇦 ON ICS3C A1.2 / BC CS10从头编写一个 for-each 循环,不使用内置方法统计字符串中的元音。🇨🇦 ON ICS3C A1.2 / BC CS10
- Explain when to use
for ch in svsfor i in range(len(s)), and give a task that requires each form. 🇨🇦 ON ICS3C A1.2解释何时使用for ch in s,何时使用for i in range(len(s)),并各举一个需要该形式的任务。🇨🇦 ON ICS3C A1.2 - Write the three-step word-count pipeline (
lower(),split(), dict loop) for a given sentence and produce the correct frequency dictionary. 🇨🇦 ON ICS3C A1.2 "count occurrences of a word"为给定句子编写三步词频统计流水线(lower()、split()、字典循环)并生成正确的频率字典。🇨🇦 ON ICS3C A1.2"计算单词出现次数" - Trace a string-expression chain (e.g.,
" Hello ".strip().lower().replace("h","j")) step by step, writing the intermediate string after each method call. 🇺🇸 AP CSP Skill 4.B逐步追踪字符串表达式链(如" Hello ".strip().lower().replace("h","j")),在每次方法调用后写出中间字符串。🇺🇸 AP CSP 技能 4.B - Extract the year, month, and day from a date string of the form
"YYYY-MM-DD"using slicing, without usingsplit(). 🇨🇦 ON ICS3C A1.2 "extract a portion"仅用切片(不用split())从"YYYY-MM-DD"格式的日期字符串中提取年、月、日。🇨🇦 ON ICS3C A1.2"提取一部分" - Honors, ICS3C / CSE1120 Write a program that removes all punctuation from a sentence before doing a word-count, producing clean frequency data. 🇨🇦 ON ICS3C A1.2 / AB CSE1120 2.6荣誉,ICS3C / CSE1120 编写一个程序,在词频统计前去除句子中的所有标点,生成干净的频率数据。🇨🇦 ON ICS3C A1.2 / AB CSE1120 2.6
What This Feeds Into本单元的去向
String manipulation is a prerequisite skill for almost every real program. Within the HS Computer Science series, the data-structures and searching units depend on your ability to tokenise text, compare strings, and loop character by character. Both downstream AP courses test string operations directly. The link below points to the AP CSA guide; AP CSA Unit 1 introduces Java String methods (which closely parallel the Python methods in this guide).字符串操作是几乎所有真实程序的先决技能。在 HS Computer Science 系列中,数据结构和搜索单元依赖于你分词、比较字符串和逐字符循环的能力。两门下游 AP 课程都直接测试字符串操作。以下链接指向 AP CSA 指南;AP CSA Unit 1 介绍 Java String 方法(与本指南中的 Python 方法高度对应)。
Within High School Computer Science.在 HS Computer Science 内部。
The Data Structures unit builds on split() and tokenisation to process lists of strings. The Searching and Sorting unit applies the character-comparison logic you practiced in §5 to sort strings alphabetically. The Software Development unit uses the same lower().strip() normalisation pipeline for input validation. AP CSP Topic 3.4 (Strings) directly tests the indexing, slicing, and method knowledge from §1–§3 of this guide.数据结构单元在 split() 和分词的基础上处理字符串列表。搜索与排序单元将 §5 中练习的字符比较逻辑应用于按字母顺序排序字符串。软件开发单元将相同的 lower().strip() 规范化流水线用于输入验证。AP CSP 主题 3.4(字符串)直接测试本指南 §1–§3 中的索引、切片和方法知识。
AP feeder links (existing in this repo).AP 衔接链接(本仓库中已有)。
AP CSP Topic 3.4 (Strings) is the matching topic: it covers string operations such as substring, concatenation and length. Skill 4.B ("Determine the result of code segments") means you must be able to predict a string expression's output without running it, exactly the tracing practice in the worked examples here.AP CSP 主题 3.4(字符串)是对应的主题:该主题涵盖子字符串、拼接、长度等字符串操作。技能 4.B("确定代码段的结果")意味着你必须能够不运行代码就预测字符串表达式的输出,正是本指南例题中练习的追踪技能。
This is the ladder we coach students up: from these high school foundations into AP and IB, and on to first-year university. If you would rather have a guide for the next step than take it on trust, Dingrui Scholars tutors teach exactly this path in one-on-one sessions and small-group classes. A free assessment is the place to start.这正是我们陪伴学生攀登的阶梯:从这些高中基础,迈入 AP 与 IB,再走向大学一年级。如果你希望在下一步有人引路,而不是凭感觉前行,Dingrui Scholars 的导师正是沿着这条路径,以一对一辅导与小班课授课。欢迎从免费评估开始。
Common Questions常见问题
Why are strings immutable in Python?为什么 Python 中字符串是不可变的?
A string is a sequence of characters, and in Python it is immutable, which means every operation that looks like a change actually returns a brand new string instead of modifying the original. Methods like upper() and replace() give you a new string back.字符串是字符的序列,在 Python 中它是不可变的,这意味着每个看似修改的操作实际上都返回一个全新的字符串,而不是改动原始字符串。upper() 和 replace() 等方法会返回一个新字符串。
What does string slicing do?字符串切片是做什么的?
Slicing extracts a portion of a string by specifying a start and end index, returning a new substring. For example, you can slice out the year, month, and day from a date string formatted as a known pattern.切片通过指定起始和结束索引来提取字符串的一部分,返回一个新的子串。例如,你可以从格式已知的日期字符串中切出年、月、日。
How do you count how many times a word appears in text?如何统计一个词在文本中出现的次数?
You can split the text into a list of words and loop through it counting occurrences, or use a dictionary that maps each word to its frequency. The dictionary approach makes updating a count an O(1) operation.你可以把文本拆成单词列表然后循环统计出现次数,或者用一个把每个词映射到出现频率的字典。字典方式让更新计数成为 O(1) 操作。
Syllabus alignment & how to use this guide大纲对照与使用说明
How to use this guide如何使用本指南
Strings are present in every curriculum, but the depth of coverage varies. AP CSP Topic 3.4 is the string topic. Ontario ICS3C A1.2 is the most explicit string-manipulation expectation, naming character swapping, capitalisation, extracting substrings, and counting occurrences, all covered here. Ontario ICS3U A1.1 covers strings as a variable type. BC has no dedicated string standard but anchors to "manipulate numbers and text" in Computer Studies 10. Alberta CSE1110/CSE1120 name strings as a data type and concatenation as an operator. The table below shows which rows are core for you; each section cites the curriculum document it was checked against.字符串出现在所有课程大纲中,但覆盖深度各有不同。AP CSP 主题 3.4 是字符串主题。安大略 ICS3C A1.2 是最明确的字符串操作期望,点名了字符交换、首字母大写、提取子字符串和计算出现次数,本指南均有涵盖。安大略 ICS3U A1.1 将字符串作为变量类型涵盖。BC 没有专门的字符串标准,但依附于 Computer Studies 10 中的"操作数字和文本"。阿尔伯塔 CSE1110/CSE1120 将字符串列为数据类型,将拼接列为运算符。下表显示哪些行对你是核心内容;每节均注明所依据的课纲文件。
| If you are in…如果你在… | Focus on these sections重点学习 | Defer / lighter可推迟 / 减负 | Source依据 |
|---|---|---|---|
| 🇺🇸 US CSTA / AP CSP美国 CSTA / AP CSP | §1 through §7 in full. AP CSP Topic 3.4 (Strings) and Skill 4.B cover string operations directly. CSTA 3B-AP-12 names strings as a fundamental data structure.§1 至 §7 完整学习。AP CSP 主题 3.4(字符串)和技能 4.B 直接涵盖字符串操作。CSTA 3B-AP-12 将字符串列为基本数据结构。 | The word-count worked example (§7) is enrichment; the core skill is reading and predicting string-expression results.词频统计例题(§7)为拓展内容;核心技能是阅读和预测字符串表达式的结果。 | CSTA K-12 and AP CSP: CSTA 3B-AP-12; AP CSP Big Idea 3 Topic 3.4; Skill 4.B:CSTA 3B-AP-12;AP CSP 大概念 3 主题 3.4;技能 4.B |
| 🇨🇦 ON Grade 11, ICS3U / ICS3C安大略 11 年级,ICS3U / ICS3C | §1 through §7. ICS3U A1.1 requires strings as a variable type (§1). ICS3C A1.2 requires character-level manipulation, substring extraction, and occurrence counting (§3, §5, §7).§1 至 §7。ICS3U A1.1 要求字符串作为变量类型(§1)。ICS3C A1.2 要求字符级操作、子字符串提取和出现次数计数(§3、§5、§7)。 | ICS3U university floor: §6 (looping over characters) and §7 (full word-count program) are enrichment; ICS3C college stream: all seven sections are in scope.ICS3U 大学预备基础:§6(遍历字符)和 §7(完整词频统计程序)为拓展;ICS3C 大学课程:全部七节均在范围内。 | ON/BC Computer Studies 11-12: ICS3U A1.1; ICS3C A1.2:ICS3U A1.1;ICS3C A1.2 |
| 🇨🇦 BC, Computer Studies 10BC,Computer Studies 10 | §1 through §4 as core (string basics, slicing, methods, formatting). §5–§7 (searching, looping, word-count) as enrichment.§1 至 §4 为核心(字符串基础、切片、方法、格式化)。§5–§7(搜索、遍历、词频统计)为拓展。 | BC has no dedicated string-processing standard; all content here sits under the general "store and manipulate numbers and text" bullet.BC 没有专门的字符串处理标准;本指南所有内容均在通用"存储和操作数字和文本"条目下。 | ON/BC Computer Studies 11-12: BC CS10 "store and manipulate numbers and text":BC CS10"存储和操作数字和文本" |
| 🇨🇦 AB, CSE1110 / CSE1120阿尔伯塔,CSE1110 / CSE1120 | §1 through §4 as core. CSE1110 outcome 2.4.3 (strings as a data type) and 2.4.6 (concatenation operators) are the assessed anchors. §5–§7 map to CSE1120 outcome 2.6 (concatenation and interpolation operators).§1 至 §4 为核心。CSE1110 结果 2.4.3(字符串作为数据类型)和 2.4.6(拼接运算符)是被评估的依据。§5–§7 对应 CSE1120 结果 2.6(拼接和插值运算符)。 | Alberta CSE has no standalone string-processing module; all content here sits within the Structured Programming 1/2 outcomes.阿尔伯塔 CSE 没有独立的字符串处理模块;本指南所有内容均在结构化编程 1/2 结果范围内。 | Alberta CTS Computing Science: CSE1110 outcomes 2.4.3, 2.4.6; CSE1120 outcome 2.6:CSE1110 结果 2.4.3、2.4.6;CSE1120 结果 2.6 |
Memorise: indexing is zero-based; slicing is s[start:stop] (stop excluded); the five key methods (upper, lower, split, join, replace); f-string syntax f"..."; and the in operator for membership testing. Read every cram-cheat box and skim the worked examples.背熟:索引从零开始;切片为 s[start:stop](stop 不含);五个关键方法(upper、lower、split、join、replace);f-string 语法 f"...";以及用于成员测试的 in 运算符。阅读每个速记框并浏览例题。
Work through all seven sections and the worked example in §7. AP CSP Skill 4.B asks you to trace string expressions step by step, practice reading s[1:4], s.split(","), and " ".join(words) without running the code. ON ICS3C A1.2 requires you to write programs that extract substrings and count occurrences from scratch.完整学习全部七节及 §7 的例题。AP CSP 技能 4.B 要求你逐步追踪字符串表达式,练习在不运行代码的情况下阅读 s[1:4]、s.split(",") 和 " ".join(words)。ON ICS3C A1.2 要求你从头编写提取子字符串和计算出现次数的程序。