Skip to content

第 3 章 字符串 ​

如果你会 JavaScript,那么字符串一定不陌生:

js
const name = "Tom";

Python 也是:

python
name = "Tom"

看起来几乎一样。

但 Python 的字符串有几个非常值得认真理解的地方:

text
字符串
  ↓
不可变
  ↓
可以索引
  ↓
可以切片
  ↓
可以迭代
  ↓
拥有大量方法

尤其是:

Python 字符串不是一个可以随便修改的字符数组。

先从最简单的开始。


3.1 字符串创建 ​

最常见的方式:

python
name = "Tom"

也可以使用单引号:

python
name = 'Tom'

两者没有本质区别。

python
a = "hello"
b = 'hello'

print(a == b)

结果:

text
True

3.1.1 为什么 Python 同时支持两种引号? ​

因为这样处理字符串中的引号会方便很多。

例如:

python
message = "I'm learning Python"

如果只能使用单引号,就需要:

python
message = 'I\'m learning Python'

反过来:

python
message = 'He said "hello"'

也很方便。

所以可以简单记:

text
"hello"
'hello'

都可以。

选择一种团队统一的代码风格即可。


3.2 字符串索引 ​

现在有一个字符串:

python
word = "Python"

它可以理解成一个字符序列:

text
 P   y   t   h   o   n
 ↑   ↑   ↑   ↑   ↑   ↑
 0   1   2   3   4   5

所以:

python
word[0]

得到:

text
'P'

而:

python
word[1]

得到:

text
'y'

3.2.1 Python 的索引从 0 开始 ​

这一点和 JavaScript 一样。

python
word = "Python"

print(word[0])
print(word[1])
print(word[5])

输出:

text
P
y
n

所以:

text
word[0] → 第一个字符
word[1] → 第二个字符
word[5] → 第六个字符

3.2.2 Python 有一个 JavaScript 没那么常用的能力:负数索引 ​

这是 Python 非常值得记住的一个小设计。

python
word = "Python"

正向:

text
 P   y   t   h   o   n
 ↑   ↑   ↑   ↑   ↑   ↑
 0   1   2   3   4   5

反向:

text
 P    y    t    h    o    n
-6   -5   -4   -3   -2   -1

所以:

python
word[-1]

得到:

text
'n'

也就是:

最后一个字符。

这非常方便。


3.2.3 为什么 -1 是最后一个? ​

因为:

text
-1 → 最后一个
-2 → 倒数第二个
-3 → 倒数第三个

例如:

python
filename = "photo.png"

print(filename[-1])
print(filename[-3:])

得到:

text
g
png

以后处理:

  • 文件名
  • 扩展名
  • 路径
  • 字符串结尾
  • 日志

时会非常方便。


3.3 字符串切片 ​

如果索引是:

拿一个字符

那么切片就是:

拿一段字符。

例如:

python
word = "Python"

取:

text
P y t

可以:

python
word[0:3]

得到:

text
'Pyt'

3.3.1 切片的基本形式 ​

python
text[start:stop]

注意:

start 包含,stop 不包含。

例如:

python
word = "Python"

word[0:3]

实际上取:

text
0
1
2

不会取:

text
3

所以:

text
Python
012345

[0:3]
 ↓
Pyt

3.3.2 为什么 stop 不包含? ​

刚开始可能觉得有点奇怪。

但这种设计非常好用。

例如:

python
word[0:2]
word[2:4]
word[4:6]

可以自然地拼起来:

text
[0:2] → Py
[2:4] → th
[4:6] → on

不会发生重叠。

于是:

python
word[0:2] + word[2:4] + word[4:6]

得到:

text
Python

这就是切片非常漂亮的地方。


3.3.3 省略 start ​

python
word[:3]

相当于:

python
word[0:3]

所以:

python
word[:3]

得到:

text
Pyt

3.3.4 省略 stop ​

python
word[3:]

表示:

从索引 3 开始,一直到结尾。

得到:

text
hon

3.3.5 复制整个字符串 ​

python
word[:]

表示:

从头到尾。

例如:

python
word = "Python"

print(word[:])

得到:

text
Python

不过对于字符串来说,通常没必要为了这个目的专门写 [:]。


3.3.6 切片支持 step ​

完整形式其实是:

python
text[start:stop:step]

例如:

python
word = "Python"

word[::2]

表示:

每隔一个字符取一个。

结果:

text
Pto

因为取的是:

text
P
t
o

索引:

text
0
2
4

3.3.7 反转字符串 ​

这是 Python 初学者最喜欢的一个技巧:

python
word[::-1]

结果:

text
nohtyP

为什么?

因为:

text
start:
省略

stop:
省略

step:
-1

也就是:

从后往前,每次走一步。

所以:

python
"Python"[::-1]

就是:

text
nohtyP

3.4 字符串是不可变对象 ​

还记得上一章讲过的:

text
immutable

吗?

字符串就是不可变对象。

所以:

python
name = "Tom"

你不能:

python
name[0] = "J"

Python 会报错。


3.4.1 那我怎么修改字符串? ​

答案是:

不能修改原来的字符串,只能创建一个新的字符串。

例如:

python
name = "Tom"

name = "Jim"

这里不是把:

text
Tom

修改成:

text
Jim

而是:

text
name ──→ "Tom"

重新变成:

text
name ──→ "Jim"

3.4.2 字符串方法为什么不会修改原字符串? ​

例如:

python
name = "tom"

upper_name = name.upper()

现在:

python
print(name)
print(upper_name)

得到:

text
tom
TOM

upper() 没有修改 name。

它返回了一个新的字符串。

因此:

python
name.upper()

更准确的理解是:

text
旧字符串
   ↓
upper()
   ↓
新字符串

这一点以后学习 List、Dict 时会产生非常重要的对比。


3.5 常用字符串方法 ​

Python 的字符串拥有大量方法。

先看看几个最常用的:

python
text = "Hello Python"

upper() ​

python
text.upper()

得到:

text
HELLO PYTHON

lower() ​

python
text.lower()

得到:

text
hello python

capitalize() ​

python
"hello world".capitalize()

得到:

text
Hello world

title() ​

python
"hello world".title()

得到:

text
Hello World

startswith() ​

判断字符串是否以某个内容开头:

python
filename = "photo.png"

filename.startswith("photo")

得到:

text
True

endswith() ​

判断结尾:

python
filename.endswith(".png")

得到:

text
True

find() ​

寻找子字符串:

python
text = "Hello Python"

text.find("Python")

得到:

text
6

因为:

text
Hello_
012345
      ↑
      P

如果找不到:

python
text.find("JavaScript")

会返回:

text
-1

count() ​

统计出现次数:

python
text = "banana"

text.count("a")

得到:

text
3

isdigit() ​

判断是不是数字字符:

python
"123".isdigit()

得到:

text
True

而:

python
"123abc".isdigit()

得到:

text
False

isalpha() ​

判断是不是字母:

python
"Python".isalpha()

得到:

text
True

3.6 split() ​

这是字符串处理中非常重要的方法。

假设:

python
text = "apple,banana,orange"

我们想得到:

python
["apple", "banana", "orange"]

可以:

python
text.split(",")

结果:

python
["apple", "banana", "orange"]

3.6.1 split() 做了什么? ​

可以把它理解成:

text
一个字符串
     ↓
按照某个分隔符切开
     ↓
多个字符串
     ↓
List

例如:

python
"a-b-c".split("-")

得到:

python
["a", "b", "c"]

3.6.2 不传参数会怎样? ​

python
text = "hello world python"

text.split()

得到:

python
["hello", "world", "python"]

默认按照空白字符进行分割。

例如:

python
"hello    world".split()

依然可以得到:

python
["hello", "world"]

这非常适合处理:

text
单词
日志
用户输入
命令行文本

3.6.3 一个非常实际的例子 ​

假设有:

python
path = "home/user/documents/report.pdf"

我们可以:

python
parts = path.split("/")

得到:

python
["home", "user", "documents", "report.pdf"]

然后:

python
parts[-1]

得到:

text
report.pdf

你已经开始把:

text
索引
+
切片
+
split

组合起来使用了。

这才是学习字符串真正有价值的地方。


3.7 join() ​

split() 很容易和 join() 搞混。

记住一个简单关系:

text
split
字符串 → List

join
List → 字符串

例如:

python
parts = ["home", "user", "documents"]

我们想重新得到:

text
home/user/documents

可以:

python
"/".join(parts)

结果:

text
home/user/documents

3.7.1 为什么是 "/".join()? ​

很多 JS 开发者第一次看到会觉得:

为什么不是 parts.join("/")?

JavaScript:

js
parts.join("/");

Python:

python
"/".join(parts)

Python 的思路是:

用谁连接,就调用谁的 join()。

所以:

python
",".join(["a", "b", "c"])

得到:

text
a,b,c

而:

python
" -> ".join(["A", "B", "C"])

得到:

text
A -> B -> C

3.7.2 split() + join() ​

这两个方法组合起来非常强。

例如:

python
text = "hello world python"

变成:

text
hello-world-python

可以:

python
result = "-".join(text.split())

发生了两步:

text
"hello world python"
        ↓
      split()
        ↓
["hello", "world", "python"]
        ↓
     "-".join()
        ↓
"hello-world-python"

这种“把数据拆开,再重新组合”的思维以后会非常常见。


3.8 replace() ​

顾名思义:

替换字符串中的内容。

例如:

python
text = "I like JavaScript"

替换:

python
text.replace("JavaScript", "Python")

得到:

text
I like Python

3.8.1 注意:原字符串没有被修改 ​

python
text = "I like JavaScript"

text.replace("JavaScript", "Python")

print(text)

仍然是:

text
I like JavaScript

因为字符串不可变。

如果需要保存结果:

python
text = text.replace("JavaScript", "Python")

3.8.2 可以限制替换次数 ​

例如:

python
text = "banana"

text.replace("a", "X", 2)

得到:

text
bXnXna

这里:

text
2

表示最多替换两次。


3.9 strip() ​

处理用户输入时,经常会遇到这种情况:

python
name = "   Tom   "

如果直接:

python
print(name)

前后都有空格。

可以:

python
name.strip()

得到:

text
Tom

3.9.1 strip() 做什么? ​

简单理解:

删除字符串两端的空白字符。

例如:

python
"   hello   ".strip()

得到:

text
"hello"

3.9.2 lstrip() 和 rstrip() ​

左边:

python
"   hello".lstrip()

得到:

text
"hello"

右边:

python
"hello   ".rstrip()

得到:

text
"hello"

所以:

text
strip()   两边
lstrip()  左边
rstrip()  右边

3.9.3 实际应用 ​

用户输入:

python
name = input("Name: ")

用户可能输入:

text
   Tom

那么:

python
name = input("Name: ").strip()

就可以把多余的首尾空格清掉。

这是一种非常常见的 Python 写法。


3.10 f-string ​

这是 Python 字符串格式化最值得优先掌握的方式。

假设:

python
name = "Tom"
age = 20

我们想输出:

text
Tom is 20 years old.

可以:

python
message = f"{name} is {age} years old."

3.10.1 和 JavaScript 对比 ​

JavaScript:

js
const name = "Tom";
const age = 20;

const message = `${name} is ${age} years old.`;

Python:

python
name = "Tom"
age = 20

message = f"{name} is {age} years old."

可以直接建立这个对应关系:

text
JS:     `...${value}...`

Python: f"...{value}..."

3.10.2 {} 里面不只是变量 ​

例如:

python
price = 10
count = 3

message = f"Total: {price * count}"

结果:

text
Total: 30

也就是说 {} 里面可以放表达式。

例如:

python
name = "tom"

print(f"Hello {name.upper()}")

得到:

text
Hello TOM

3.10.3 格式化数字 ​

例如:

python
price = 19.9999

print(f"{price:.2f}")

得到:

text
20.00

这里:

text
:.2f

表示:

保留两位小数。


千位分隔符 ​

python
number = 1000000

print(f"{number:,}")

得到:

text
1,000,000

这在显示:

  • 金额
  • 数据量
  • 文件大小
  • 统计结果

时非常有用。


3.11 多行字符串 ​

有时候我们需要保存一大段文本。

例如:

python
message = """
Hello.

Welcome to Python.

Have a nice day!
"""

Python 使用:

text
"""
...
"""

表示多行字符串。

也可以:

python
message = '''
Hello.

Welcome to Python.
'''

3.11.1 为什么多行字符串有用? ​

例如:

python
sql = """
SELECT *
FROM users
WHERE age > 18
"""

或者:

python
html = """
<div>
    <h1>Hello</h1>
</div>
"""

再比如生成:

text
Prompt
Markdown
SQL
HTML
配置文件
邮件正文

都会很方便。


3.12 字符串格式化 ​

除了 f-string,Python 还有其他格式化方式。

了解它们即可。


3.12.1 f-string —— 首选 ​

python
name = "Tom"
age = 20

f"{name} is {age} years old."

现代 Python 中,通常优先使用它。


3.12.2 format() ​

以前非常常见:

python
"{} is {} years old.".format(name, age)

也可以使用名字:

python
"{name} is {age} years old.".format(
    name=name,
    age=age
)

现在新代码通常更推荐 f-string。


3.12.3 % 格式化 ​

更老的代码中可能看到:

python
"Hello %s" % name

这种写法现在通常不作为首选。

但你以后读旧项目时可能会遇到。

所以:

会看就够了,不需要优先学习。


3.13 split() 和 join() 是一对好朋友 ​

这个关系非常值得单独记住。

例如:

python
text = "Python is awesome"

拆开:

python
words = text.split()

得到:

python
["Python", "is", "awesome"]

重新连接:

python
"-".join(words)

得到:

text
Python-is-awesome

所以:

text
            split()
字符串 ─────────────────→ List
                            │
                            │
                         join()
                            ↓
                          字符串

这是一种非常常见的数据转换模式。


3.14 JavaScript → Python 字符串对照 ​

操作JavaScriptPython
长度str.lengthlen(str)
转大写str.toUpperCase()str.upper()
转小写str.toLowerCase()str.lower()
查找str.indexOf(x)str.find(x)
替换str.replace()str.replace()
分割str.split()str.split()
连接arr.join()separator.join()
去空白str.trim()str.strip()
开头判断str.startsWith()str.startswith()
结尾判断str.endsWith()str.endswith()
字符串插值`${x}`f"{x}"
反转常用 split/reverse/join 等方式str[::-1]

这里有一个特别值得注意的区别:

text
JS:
array.join(separator)

Python:
separator.join(iterable)

不要机械地把 JS 的:

js
items.join(",")

翻译成:

python
items.join(",")

Python 中应该:

python
",".join(items)

3.15 字符串最重要的几个思维模型 ​

到这里,我们可以把字符串重新理解一遍。

模型一:字符串是序列 ​

python
word = "Python"

可以:

python
word[0]
word[1]
word[-1]

所以它是一个:

text
可索引的序列

模型二:字符串可以切片 ​

python
word[:3]
word[2:]
word[::2]
word[::-1]

切片的基本形式:

text
[start:stop:step]

模型三:字符串不可变 ​

python
word[0] = "J"

不允许。

字符串方法通常返回新的字符串:

python
new_word = word.upper()

而不是修改 word。


模型四:字符串方法是在做转换 ​

例如:

text
upper()
    ↓
字符串 → 新字符串

split()
    ↓
字符串 → List

join()
    ↓
List → 字符串

replace()
    ↓
字符串 → 新字符串

strip()
    ↓
字符串 → 新字符串

这样理解,比死记每个 API 更有用。


3.16 本章总结 ​

这一章真正需要掌握的不是几十个字符串 API。

而是下面这张图:

text
                    str
                     │
          ┌──────────┼──────────┐
          ↓          ↓          ↓
        索引        切片       方法
          │          │          │
       word[0]    word[1:4]   upper()
                                  │
              ┌───────────────────┼────────────────┐
              ↓                   ↓                ↓
           split()             replace()        strip()
              │
              ↓
             List
              │
              ↓
           join()
              │
              ↓
            str

最值得记住:

text
1. 字符串是序列

2. 索引从 0 开始

3. 可以使用负数索引

4. 切片使用 [start:stop:step]

5. stop 不包含

6. [::-1] 可以反转字符串

7. str 是不可变对象

8. split():字符串 → List

9. join():List → 字符串

10. replace() 不会修改原字符串

11. strip() 用于清理首尾空白

12. f-string 是现代 Python 最常用的字符串格式化方式

本章练习 ​

练习 1:索引 ​

给出:

python
text = "JavaScript"

分别获取:

text
第一个字符
最后一个字符
倒数第二个字符

要求使用索引。


练习 2:切片 ​

给出:

python
text = "JavaScript"

获取:

text
Java
Script

然后尝试:

python
text[::-1]

看看结果。


练习 3:清理用户输入 ​

给出:

python
name = "   Tom   "

得到:

text
Tom

要求使用:

python
strip()

练习 4:拆分路径 ​

给出:

python
path = "home/user/documents/report.pdf"

使用 split() 得到:

python
["home", "user", "documents", "report.pdf"]

然后获取:

text
report.pdf

练习 5:重新组合 ​

给出:

python
words = ["Python", "is", "awesome"]

得到:

text
Python-is-awesome

要求使用:

python
join()

练习 6:统计单词 ​

给出:

python
text = "Python is easy to learn"

要求:

  1. 使用 split() 拆分
  2. 统计单词数量
  3. 输出每个单词

最终应该得到类似:

text
5
Python
is
easy
to
learn

练习 7:f-string ​

定义:

python
name = "Tom"
age = 25
job = "developer"

使用 f-string 输出:

text
My name is Tom, I am 25 years old, and I am a developer.

思考题:为什么 Python 的字符串设计得这么好? ​

最后留一个问题。

看看:

python
text = "hello world"

words = text.split()

现在:

text
text
 ↓
"hello world"

words
 ↓
["hello", "world"]

然后:

python
text = "-".join(words)

得到:

text
hello-world

整个过程实际上体现了 Python 一个非常重要的思想:

让数据转换尽可能直接地表达你的意图。

你不需要写一堆循环:

python
result = ""

for word in words:
    ...

很多时候,只需要:

python
"-".join(words)

这也是为什么 Python 代码经常看起来非常短。

但这里还有一个更值得深入的问题:

Python 为什么有 str、list、tuple 这么多“序列”?它们之间到底有什么区别?

下一章我们就从这里进入 Python 最重要的数据结构之一:

text
List
 ↓
创建
 ↓
索引
 ↓
切片
 ↓
修改
 ↓
append()
 ↓
extend()
 ↓
insert()
 ↓
remove()
 ↓
pop()
 ↓
排序
 ↓
复制
 ↓
List Comprehension

而且这一章会真正让你理解:

为什么字符串不能修改,但 List 可以修改。