六十道聚焦 Python 字符串常用方法的练习题,覆盖大小写转换、查找统计、判断检测、对齐填充、分割拼接与修剪转换。每题附参考答案与解析,先动手写,再对照答案。
60 题 · 6 个模块 · 由浅入深 · 含解析
模块一:大小写转换
热身。
upper / lower / title / capitalize / swapcase / casefold一组转换方法,再认识对应的istitle / isupper / islower判断。注意capitalize会把其余字母强制小写。
01. 已知 words = "hello world",调用方法输出全大写。
期望输出:
text
HELLO WORLD
参考答案:
python
words.upper()
解析:
upper()把所有英文字母转大写。中文、数字、标点不受影响。这是你main.py里练过的同款方法。
02. 已知 words = "HELLO WORLD",输出全小写。
期望输出:
text
hello world
参考答案:
python
words.lower()
解析:
lower()与upper()是一对,全转小写。只处理有大小写之分的字符,数字符号原样保留。
03. 已知 words = "hello world",让每个单词首字母大写。
期望输出:
text
Hello World
参考答案:
python
words.title()
解析:
title()每个单词首字母大写、其余小写。单词按空白/标点分隔,因此"he's"会变"He'S"------这是title()的已知坑,正式文本可用string.capwords()。
04. 已知 words = "hello world",让整个字符串的首字母大写,其余全小写。
期望输出:
text
Hello world
参考答案:
python
words.capitalize()
解析: 易错点 :
capitalize()只有第一个字符大写,后面全部强制小写。与title()的区别:capitalize只管句首,title管每个单词首。"hELLO"→"Hello"。
05. 已知 words = "Hello World",大小写互换。
期望输出:
text
hELLO wORLD
参考答案:
python
words.swapcase()
解析:
swapcase()大写变小写、小写变大写。可用于简单的大小写翻转,正式场景少用,因为它不是 round-trip(再 swap 不一定回原样)。
06. 已知 s = "Straße",用忽略大小写的方式转成全小写形式,使 ß 被正确展开为 ss。
期望输出:
text
strasse
参考答案:
python
s.casefold()
解析:
casefold()比lower()更激进,会把ß→ss。做忽略大小写的字符串匹配(如搜索、对比)时,应用casefold()而非lower(),这是国际化的正确做法。
07. 已知 words = "Hello World",判断是否每个单词首字母都大写。
期望输出:
text
True
参考答案:
python
words.istitle()
解析:
istitle()检查是否符合title()规范:每个单词首字母大写、其余小写。"Hello World"→ True。它是title()的逆判断。
08. 已知 words = "hello world",判断是否每个单词首字母都大写。
期望输出:
text
False
参考答案:
python
words.istitle()
解析: 首字母都是小写 → False。注意
"Hello world"(第二个单词首小写)也是 False,istitle要求每个单词都达标。
09. 已知 s = "HELLO",判断是否全大写。
期望输出:
text
True
参考答案:
python
s.isupper()
解析:
isupper()要求所有字母都大写,非字母字符忽略。因此"HELLO123".isupper()也是 True------数字不影响判断。
10. 已知 s = "Hello",判断是否全小写。
期望输出:
text
False
参考答案:
python
s.islower()
解析:
"Hello"含大写 H → False。"hello123".islower()→ True(数字被忽略)。islower()是lower()的判断伴侣。
模块二:查找与统计
find与index的区别(找不到时返回 -1 还是报错)、rfind从右找、count带范围参数、startswith/endswith支持元组匹配。
11. 已知 words = "hello world",查找字符 'o' 第一次出现的位置。
期望输出:
text
4
参考答案:
python
words.find('o')
解析:
find()从左往右找,返回首次出现的正向索引。"hello" 的 o 在索引 4。找不到返回 -1,不报错------这是find与index的核心区别。
12. 已知 words = "hello world",从索引 5 开始查找字符 'o'。
期望输出:
text
7
参考答案:
python
words.find('o', 5)
解析:
find()第二参数指定起始位置。从索引 5(即" world")开始找,第一个 o 在索引 7(world 的 o)。还可加第三参数end限定结束。
13. 已知 words = "hello world",查找不存在的字符 'x'。
期望输出:
text
-1
参考答案:
python
words.find('x')
解析:
find()找不到时返回 -1(不报错)。做容错查找优先用find,配合if pos != -1判断存在性。
14. 已知 words = "hello world",从右侧查找字符 'o' 的位置。
期望输出:
text
7
参考答案:
python
words.rfind('o')
解析:
rfind()从右往左找,但返回的仍是正向索引 。world 的 o 在索引 7,它是最后一个 o,所以rfind也返回 7。取路径里最后一个分隔符时常配rfind。
15. 已知 words = "hello world",用 index() 查找字符 'o'。
期望输出:
text
4
参考答案:
python
words.index('o')
解析:
index()与find()用法相同,区别仅在找不到时:index()抛ValueError,find()返回 -1。确定存在时才用index,不确定就用find。
16. 已知 words = "hello world",统计字符 'o' 出现的次数。
期望输出:
text
2
参考答案:
python
words.count('o')
解析:
count()统计子串出现次数。hello world 有两个 o(hello 的、world 的),返回 2。参数也可是多字符子串,如count('ll')。
17. 已知 words = "hello world",只在 [0, 5) 范围内统计 'o'。
期望输出:
text
1
参考答案:
python
words.count('o', 0, 5)
解析:
count()可指定起止范围。[0,5)即 "hello",只含 1 个 o。用于分段统计、局部计数,避免再切片。
18. 已知 words = "hello world",判断是否以 "hello" 开头。
期望输出:
text
True
参考答案:
python
words.startswith('hello')
解析:
startswith()判断前缀。可指定起始位置:words.startswith('world', 6)也为 True。判断协议头(http://)、文件类型时常用。
19. 已知 words = "hello world",判断是否以 "world" 结尾。
期望输出:
text
True
参考答案:
python
words.endswith('world')
解析:
endswith()判断后缀。判断文件扩展名、匹配结尾标记最常用。与startswith是一对。
20. 已知 filename = "photo.png",判断是否以 .jpg 或 .png 结尾。
期望输出:
text
True
参考答案:
python
filename.endswith(('.jpg', '.png'))
解析:
startswith / endswith可传元组 ,匹配任一即 True。批量判断文件类型一行搞定,比filename.endswith('.jpg') or filename.endswith('.png')优雅得多。
模块三:判断检测
经典考点 :
isdigit / isdecimal / isnumeric三者范围不同,务必对比着记(严格程度 isdecimal < isdigit < isnumeric)。其余is系列逐个上手。
21. 已知 s = "hello",判断是否全由字母组成。
期望输出:
text
True
参考答案:
python
s.isalpha()
解析:
isalpha()要求全部是字母(中文也算字母)。含空格、数字、标点则 False。"hello".isalpha()→ True。
22. 已知 s = "hello123",判断是否全由字母组成。
期望输出:
text
False
参考答案:
python
s.isalpha()
解析: 含数字 → False。
isalpha()严格只认字母。要"字母或数字"用isalnum()。验证纯字母用户名、姓名时常用isalpha()。
23. 已知 s = "123",判断是否为数字字符。
期望输出:
text
True
参考答案:
python
s.isdigit()
解析:
isdigit()对 "123" 返回 True。它还认上标数字如"²",范围比isdecimal大。这是你main.py里练过的。
24. 已知 s = "123",判断是否为十进制数字字符。
期望输出:
text
True
参考答案:
python
s.isdecimal()
解析:
isdecimal()最严格,只认 0-9 风格的十进制字符。"123" → True,但上标"²"→ False。判断能否安全转 int 时用它最稳。
25. 已知 s = "123",判断是否为数值字符。
期望输出:
text
True
参考答案:
python
s.isnumeric()
解析:
isnumeric()范围最广,连罗马数字、分数符都算。"123" → True。它最宽松,做"纯数字校验"反而不够严格。
26. 已知 s = "²"(上标 2),对比 isdigit 与 isdecimal 的返回值,体会区别。
期望输出:
text
isdigit: True, isdecimal: False
参考答案:
python
f"isdigit: {s.isdigit()}, isdecimal: {s.isdecimal()}"
解析: 经典考点 !
"²"的isdigit()是 True,isdecimal()是 False,isnumeric()是 True。严格程度:isdecimal < isdigit < isnumeric。判断"能转 int"只用isdecimal。
27. 已知 s = "²",判断是否为数值字符。
期望输出:
text
True
参考答案:
python
s.isnumeric()
解析:
isnumeric()范围最广,上标、罗马数字、分数符都返回 True。所以它单独判断"是否纯数字"不够准,需配合isdecimal才严谨。
28. 已知 s = "abc123",判断是否全由字母和数字组成。
期望输出:
text
True
参考答案:
python
s.isalnum()
解析:
isalnum()≈isalpha() or isdigit()的并集。只要全是字母或数字就 True,含空格/标点则 False。校验用户名、变量名可用。
29. 已知 s = " "(三个空格),判断是否全为空白字符。
期望输出:
text
True
参考答案:
python
s.isspace()
解析:
isspace()认空格、制表符\t、换行\n等所有空白。空字符串""返回 False。判断空行、清洗空白行常用。
30. 已知 s = "my_var_2",判断是否为合法标识符。
期望输出:
text
True
参考答案:
python
s.isidentifier()
解析:
isidentifier()检查是否符合变量命名规则:字母/下划线开头,后跟字母数字下划线。但不检测关键字 ,"if"也会返回 True。
31. 已知 s = "2things",判断是否为合法标识符。
期望输出:
text
False
参考答案:
python
s.isidentifier()
解析: 数字开头不合法 → False。
isidentifier()只看命名规则,不看是否是保留字。要排除关键字,再配keyword.iskeyword(s)。
32. 已知 s = "Hello",判断是否全由 ASCII 字符组成;再判断中文 "你好"。
期望输出:
text
True / False
参考答案:
python
# "Hello".isascii() → True; "你好".isascii() → False
s.isascii()
"你好".isascii()
解析:
isascii()是 Python 3.7+ 的方法,只认 0-127 的 ASCII 字符。"Hello" → True,"你好" → False。用于判断是否需要特殊编码处理、是否纯英文。
模块四:对齐与填充
center / ljust / rjust / zfill。注意zfill对符号的特殊处理(0 补在符号后),以及center在偶数剩余宽时右侧多分配一个。
33. 已知 words = "hello",居中占 11 字符宽(用方括号框住看空格)。
期望输出:
text
[ hello ]
参考答案:
python
f"[{words.center(11)}]"
解析:
center(11)把 5 字符放中间,左右各补 3 空格(剩余 6,左右各 3)。默认填充字符是空格。这是你main.py里练过的。
34. 已知 words = "hello",左对齐占 10 字符宽。
期望输出:
text
[hello ]
参考答案:
python
f"[{words.ljust(10)}]"
解析:
ljust(10)左对齐,右侧补空格凑满 10。对齐表格左列(名称、标题)常用。等价于 f-string 的{words:<10}。
35. 已知 words = "hello",右对齐占 10 字符宽。
期望输出:
text
[ hello]
参考答案:
python
f"[{words.rjust(10)}]"
解析:
rjust(10)右对齐,左侧补空格。对齐数字列、右对齐文本常用。等价于 f-string 的{words:>10}。
36. 已知 num = "42"(字符串),左侧补零占 5 位。
期望输出:
text
00042
参考答案:
python
num.zfill(5)
解析:
zfill(5)用 0 在左侧填充到宽 5。注意它对字符串操作 (不是数字)。生成编号、补零工号、固定长流水号常用。这是你main.py里练过的。
37. 已知 words = "hello",用 - 填充居中占 11 宽。
期望输出:
text
---hello---
参考答案:
python
words.center(11, '-')
解析:
center第二参数指定填充字符。5 字符占 11 宽,左右各 3 个-。做分隔标题行、装饰性边框常用。
38. 已知 num = "-42"(带负号的字符串),左侧补零占 5 位,注意符号位置。
期望输出:
text
-0042
参考答案:
python
num.zfill(5)
解析: 关键行为 :
zfill遇到符号(+/-)时,0 补在符号之后 而非之前,所以"-42".zfill(5)→"-0042",负号始终在最前。补零负数编号时要知道这点。
39. 已知 words = "hello",用 * 填充居中占 10 宽,体会偶数剩余宽的分配。
期望输出:
text
**hello***
参考答案:
python
words.center(10, '*')
解析: 10 宽放 5 字符剩 5,偶数时左 2 右 3(右侧多 1 )→
**hello***。这是center的固定规则:剩余奇数时左右各半,偶数时右侧多分配一个。
40. 已知 nums = [3, 12, 7],逐行右对齐占 4 位,让个位对齐。
期望输出:
text
3
12
7
参考答案:
python
for x in nums:
print(str(x).rjust(4))
解析:
rjust(4)让数字右对齐 4 位,个位自然对齐。需先str()转字符串再对齐(或直接用 f-string{x:>4})。打印对齐的数值列常用。
模块五:分割与拼接
split与join互为逆操作;partition切一刀返回三元组;splitlines按行分割;replace可限制替换次数。本节是数据清洗的高频方法。
41. 已知 s = "a,b,c",按逗号分割成列表。
期望输出:
text
['a', 'b', 'c']
参考答案:
python
s.split(',')
解析:
split(',')按逗号分割,返回列表。解析 CSV、分割配置最常用。分隔符被消费,不出现在结果里。
42. 已知 s = "a,b,,c",按逗号分割,体会空字段。
期望输出:
text
['a', 'b', '', 'c']
参考答案:
python
s.split(',')
解析: 连续分隔符会产生空字符串元素
''。CSV 含空字段时常这样,后续需注意空值的判断与转换,别当 None 处理。
43. 已知 s = " hello world ",用无参 split 清理并分词。
期望输出:
text
['hello', 'world']
参考答案:
python
s.split()
解析:
split()无参时按任意空白分割,且自动忽略首尾和连续空白。这是它和split(' ')的关键区别------后者会保留空字段。
44. 已知 s = "a,b,c,d",只分割 1 次。
期望输出:
text
['a', 'b,c,d']
参考答案:
python
s.split(',', 1)
解析: 第二参数
maxsplit限制分割次数。split(',', 1)只切第一刀,右边整体保留。解析「键,值」、把第一段当 key 其余当 value 时很有用。
45. 已知 lines = "a\nb\nc",按行分割成列表。
期望输出:
text
['a', 'b', 'c']
参考答案:
python
lines.splitlines()
解析:
splitlines()按各种换行符(\n、\r\n、\r)分割,且不保留行尾分隔符。比split('\n')更通用,跨平台处理文本行首选。
46. 已知 parts = ['a', 'b', 'c'],用逗号拼接成字符串。
期望输出:
text
a,b,c
参考答案:
python
','.join(parts)
解析:
join()是split()的逆操作。注意语法 :分隔符在前'sep'.join(list),不是list.join()。拼路径用'/'.join,拼 CSV 用','.join。
47. 已知 s = "hello world",用 partition 分割首次出现的空格。
期望输出:
text
('hello', ' ', 'world')
参考答案:
python
s.partition(' ')
解析:
partition()返回三元组(前、分隔符、后),总是 3 个元素 。找不到分隔符时后两项为空串。适合「切一刀」的场景,比split更结构化。
48. 已知 s = "hello world foo",用 rpartition 从右分割首次空格。
期望输出:
text
('hello world', ' ', 'foo')
参考答案:
python
s.rpartition(' ')
解析:
rpartition()从右找分隔符,切最后一刀。解析「路径/文件名」「域名/路径」时常用:取最后一段做文件名,前面整体做目录。
49. 已知 s = "hello world",把所有 'o' 替换为 '0'。
期望输出:
text
hell0 w0rld
参考答案:
python
s.replace('o', '0')
解析:
replace(旧, 新)替换全部匹配,可替换多字符子串。字符串不可变,replace返回新串不改原串------这是字符串方法的共同特性。
50. 已知 s = "hello",只替换第一个 'l' 为 'L'。
期望输出:
text
heLlo
参考答案:
python
s.replace('l', 'L', 1)
解析:
replace第三参数count限制替换次数。replace('l','L',1)只换第一个 l。做受限替换、敏感词部分打码、批量改首处匹配时用。
模块六:修剪与转换映射
strip家族去首尾字符;maketrans + translate做批量映射/删除;removeprefix / removesuffix(3.9+)安全移除前后缀;最后一题综合清洗实战。
51. 已知 s = " hello ",去除两侧空白。
期望输出:
text
hello
参考答案:
python
s.strip()
解析:
strip()去除两侧的空白(空格、制表、换行)。无参时去所有空白字符。这是最常用的清洗方法,读用户输入、解析数据时几乎必用。
52. 已知 s = "###hello###",去除两侧的 #。
期望输出:
text
hello
参考答案:
python
s.strip('#')
解析:
strip(字符)去除两侧指定字符。注意去的是「字符集合」中任意字符,不是整体匹配 ------"#.#".strip('#.')会变空串。处理 Markdown 标题、引号包裹常用。
53. 已知 s = " hello ",只去除左侧空白。
期望输出:
text
hello
参考答案:
python
s.lstrip()
解析:
lstrip()只去左侧。注意保留下来的尾部空格 仍在那里(输出hello尾随两空格)。用于去前导空白但保留尾部对齐时。
54. 已知 s = " hello ",只去除右侧空白。
期望输出:
text
hello
参考答案:
python
s.rstrip()
解析:
rstrip()只去右侧。读文件每行后常line.rstrip('\n')去行尾换行。保留前导缩进(如代码缩进)时用它。
55. 已知 s = "hello",建立 h→H、e→3 的映射并转换。
期望输出:
text
H3llo
参考答案:
python
s.translate(str.maketrans({'h': 'H', 'e': '3'}))
解析:
maketrans(字典)建映射表,translate()应用它。一次替换多个不同字符,比多次replace高效清晰。这是你main.py里translate的进阶用法。
56. 已知 s = "hello, world!",删除所有标点符号。
期望输出:
text
hello world
参考答案:
python
# 需先 import string;string.punctuation 是全部标点集合
import string
s.translate(str.maketrans('', '', string.punctuation))
解析:
maketrans(从, 到, 删除)第三参数指定要删除的字符集合。这里把标点全删。删除批量字符比循环replace高效。这正是你main.py最后一行练的。
57. 已知 s = "HelloWorld",移除前缀 "Hello"(Python 3.9+)。
期望输出:
text
World
参考答案:
python
s.removeprefix('Hello')
解析:
removeprefix()移除指定前缀(3.9+)。比切片s[5:]更安全:不匹配时原样返回,不会误删。处理带固定前缀的批量数据很顺手。
58. 已知 s = "photo.jpg",移除后缀 ".jpg"。
期望输出:
text
photo
参考答案:
python
s.removesuffix('.jpg')
解析:
removesuffix()移除后缀(3.9+)。比s[:-4]安全:不匹配原样返回。批量去文件扩展名常用。和removeprefix是一对。
59. 已知 s = " hello world ",用 split + join 把多个空格压缩成一个。
期望输出:
text
hello world
参考答案:
python
' '.join(s.split())
解析:
split()自动合并连续空白并去首尾,join再用单空格拼回。这是压缩多余空白的标准一行写法,清洗用户输入、规范化文本高频使用。
60. 已知 raw = " Tom, 18, 95.5 "(带多余空格的记录),清洗后输出「Tom 的成绩是 95.5」。
期望输出:
text
Tom 的成绩是 95.5
参考答案:
python
# split 拆三段 → strip 清洗每段 → f-string 格式化输出
name, age, score = (x.strip() for x in raw.split(','))
f"{name} 的成绩是 {float(score):.1f}"
解析: 综合实战!
split(',')拆三段 → 生成器strip清洗每段 → f-string 把 score 转 float 再.1f格式化。这正是真实数据清洗的缩影:分割、修剪、格式化三连。
练习手册 · 60 题 · 字符串常用方法
建议:先独立写答案,再对照参考答案。错题回看对应模块的解析。
进阶方向:
bytes / bytearray的字节方法、re正则、textwrap文本包装,可按需拓展。
专注于原创短更,便于碎片化涉猎知识。希望我走过的路,留下的痕迹,能对你有所启发和帮助。 转发请注明原处,平台投稿请私信。