目录/第 07 章 · str 方法补充
第 07 章 / 70 · 入门 · 数据结构与基础

str 方法补充

removeprefix / isdigit / lstrip / partition 等课堂用法

先介绍1 个 demo6 个任务答案可展开

一、本章介绍

课堂第 2、7 章用到了很多字符串方法:upper/lower、strip/lstrip、split/join、replace/find、title、removeprefix/removesuffix、startswith、isdigit 等。这些方法都不改原字符串,而是返回新结果。

这一章补齐课堂里出现但前面 str 章没细讲的方法,用 6 个任务练熟。

本章要点

  • removeprefix/removesuffix 去前后缀
  • isdigit 判断数字
  • lstrip/rstrip 单边去空白
  • find 查找位置
  • partition 分割三段

二、先看 demo

下面这个例子把本章涉及的用法尽量全面地串了一遍,代码带逐行注释,可以直接复制到本地 .py 文件运行。

案例

先看一个完整例子

介绍 · 逐行注释
s = "  hello world  "
print(s.strip())
print(s.lstrip())
print("test.py".removesuffix(".py"))
print("123".isdigit(), "12a".isdigit())
print("abc".find("c"))
print("a=b=c".partition("="))
运行结果
hello world
hello world  
test
True False
2
('a', '=', 'b=c')

要点:removeprefix/removesuffix 精确去前后缀比 replace 更安全;partition 返回(前,分隔符,后)三元组。

三、6 个任务(自己先写,再看答案)

难度从入门到挑战逐步增加。每个任务的答案默认折叠,点开可看参考代码、运行结果;有第二种解法的也一并给出。代码都可以直接运行。

任务 1

去前缀

自己写 · 附答案入门 ★☆☆
解题提示:本题主要用到 removeprefix/removesuffix 去前后缀、isdigit 判断数字、lstrip/rstrip 单边去空白。先对照要求自己写一遍,卡住了再展开答案。

用 removeprefix 去掉 "pre_test" 的 "pre_"

我的代码草稿(可复制到本地 .py 文件运行)
参考答案(先自己写,再看)
参考答案一
print("pre_test".removeprefix("pre_"))
运行结果
test
参考答案二(另一种解法)
s="pre_test"
print(s[4:] if s.startswith("pre_") else s)
任务 2

去后缀

自己写 · 附答案入门 ★☆☆
解题提示:本题主要用到 removeprefix/removesuffix 去前后缀、isdigit 判断数字、lstrip/rstrip 单边去空白。先对照要求自己写一遍,卡住了再展开答案。

用 removesuffix 去掉 "data.csv" 的 ".csv"

我的代码草稿(可复制到本地 .py 文件运行)
参考答案(先自己写,再看)
参考答案一
print("data.csv".removesuffix(".csv"))
运行结果
data
参考答案二(另一种解法)
print("data.csv".rsplit(".",1)[0])
任务 3

判断数字

自己写 · 附答案进阶 ★★☆
解题提示:本题主要用到 removeprefix/removesuffix 去前后缀、isdigit 判断数字、lstrip/rstrip 单边去空白。先对照要求自己写一遍,卡住了再展开答案。

用 isdigit 判断 "2024" 和 "2a"

我的代码草稿(可复制到本地 .py 文件运行)
参考答案(先自己写,再看)
参考答案一
print("2024".isdigit(), "2a".isdigit())
运行结果
True False
参考答案二(另一种解法)
print("2024".isnumeric(), "2a".isnumeric())
任务 4

单边去空白

自己写 · 附答案进阶 ★★☆
解题提示:本题主要用到 removeprefix/removesuffix 去前后缀、isdigit 判断数字、lstrip/rstrip 单边去空白。先对照要求自己写一遍,卡住了再展开答案。

用 lstrip 去掉 " hi" 左边空白

我的代码草稿(可复制到本地 .py 文件运行)
参考答案(先自己写,再看)
参考答案一
print(repr("  hi".lstrip()))
运行结果
'hi'
参考答案二(另一种解法)
print(repr("  hi".strip()))
任务 5

查找位置

自己写 · 附答案挑战 ★★★
解题提示:本题主要用到 removeprefix/removesuffix 去前后缀、isdigit 判断数字、lstrip/rstrip 单边去空白。先对照要求自己写一遍,卡住了再展开答案。

用 find 找 "banana" 里 "na" 第一次出现的位置

我的代码草稿(可复制到本地 .py 文件运行)
参考答案(先自己写,再看)
参考答案一
print("banana".find("na"))
运行结果
2
参考答案二(另一种解法)
print("banana".index("na"))
任务 6

三段分割

自己写 · 附答案挑战 ★★★
解题提示:本题主要用到 removeprefix/removesuffix 去前后缀、isdigit 判断数字、lstrip/rstrip 单边去空白。先对照要求自己写一遍,卡住了再展开答案。

用 partition 把 "a:b" 按 : 分成三段

我的代码草稿(可复制到本地 .py 文件运行)
参考答案(先自己写,再看)
参考答案一
print("a:b".partition(":"))
运行结果
('a', ':', 'b')
参考答案二(另一种解法)
s="a:b"; p=s.index(":"); print((s[:p], s[p], s[p+1:]))