Python 教程 07:字符串深入

“语言是思维的外壳。”

字符串是编程中最常用的数据类型之一,几乎每个程序都要处理文本。今天我们深入学习 Python 字符串的各种操作,从格式化到正则表达式,让你处理文本得心应手。

1. 字符串的创建

Python 中创建字符串有多种方式:

 1# 单引号
 2s1 = 'Hello'
 3
 4# 双引号
 5s2 = "World"
 6
 7# 三引号(多行字符串)
 8s3 = """这是一个
 9多行
10字符串"""
11
12s4 = '''也可以用
13单引号'''
14
15# 原始字符串(忽略转义字符)
16path = r"C:\Users\name\documents"  # \n不会被解释为换行
17
18# 字符串拼接
19full = s1 + " " + s2  # "Hello World"

2. 字符串格式化:三种武器

方法 1:%格式化(老式,不推荐)

1name = "张三"
2age = 25
3print("我叫%s,今年%d岁" % (name, age))
4
5# 格式控制
6pi = 3.14159
7print("π = %.2f" % pi)  # 保留2位小数

方法 2:format()方法

 1# 位置参数
 2print("{}+{}={}".format(1, 2, 3))
 3
 4# 索引
 5print("{0}+{1}={2}".format(1, 2, 3))
 6print("{2}+{1}={0}".format(3, 2, 1))  # 调换顺序
 7
 8# 关键字参数
 9print("{name}今年{age}岁".format(name="李四", age=30))
10
11# 格式控制
12print("{:.2f}".format(3.14159))  # 3.14
13print("{:0>5}".format(42))      # 00042(左侧填充0,总宽度5)
14print("{:*^10}".format("Hi"))   # ****Hi****(居中,宽度10,填充*)

方法 3:f-string(Python 3.6+,最推荐)

 1name = "王五"
 2age = 28
 3city = "北京"
 4
 5# 简洁直观
 6print(f"{name}今年{age}岁,来自{city}")
 7
 8# 表达式
 9print(f"明年我{age + 1}岁")
10print(f"2的10次方是{2 ** 10}")
11
12# 格式控制
13pi = 3.14159
14print(f"π ≈ {pi:.2f}")
15
16# 对齐和填充
17num = 42
18print(f"{num:0>5}")   # 00042
19print(f"{num:*^10}")  # ****42****
20
21# 调试输出(Python 3.8+)
22x = 10
23print(f"{x=}")  # x=10

推荐:新代码统一使用 f-string,简洁且高效。

3. 字符串索引和切片

字符串可以像列表一样索引和切片:

 1text = "Python"
 2
 3# 索引(从0开始)
 4print(text[0])   # 'P'
 5print(text[-1])  # 'n'(倒数第一个)
 6print(text[-2])  # 'o'(倒数第二个)
 7
 8# 切片 [start:stop:step]
 9print(text[0:3])   # 'Pyt'(0到2,不含3)
10print(text[:3])    # 'Pyt'(省略start默认为0)
11print(text[3:])    # 'hon'(省略stop默认到末尾)
12print(text[:])     # 'Python'(复制整个字符串)
13
14# 步长
15print(text[::2])   # 'Pto'(每隔一个字符)
16print(text[::-1])  # 'nohtyP'(反转字符串)
17
18# 负索引切片
19print(text[-3:])   # 'hon'(最后3个字符)

字符串反转s[::-1]是 Python 的经典技巧。

4. 字符串方法:工具箱

Python 提供了丰富的字符串方法:

大小写转换

1s = "Hello World"
2
3print(s.upper())       # 'HELLO WORLD'
4print(s.lower())       # 'hello world'
5print(s.capitalize())  # 'Hello world'(首字母大写)
6print(s.title())       # 'Hello World'(每个单词首字母大写)
7print(s.swapcase())    # 'hELLO wORLD'(大小写互换)

查找和替换

 1s = "Python is awesome, Python is easy"
 2
 3# 查找
 4print(s.find("Python"))      # 0(第一次出现的位置)
 5print(s.find("Java"))        # -1(没找到)
 6print(s.count("Python"))     # 2(出现次数)
 7
 8# 替换
 9print(s.replace("Python", "Go"))  # 全部替换
10print(s.replace("Python", "Go", 1))  # 只替换第1个

分割和连接

 1# 分割
 2s = "apple,banana,orange"
 3fruits = s.split(",")  # ['apple', 'banana', 'orange']
 4
 5s2 = "Hello   World"
 6words = s2.split()  # ['Hello', 'World'](按空白符分割)
 7
 8# 连接
 9fruits = ["apple", "banana", "orange"]
10result = ",".join(fruits)  # "apple,banana,orange"
11
12# 分行
13text = "第一行\n第二行\n第三行"
14lines = text.splitlines()  # ['第一行', '第二行', '第三行']

去除空白

1s = "  Hello World  \n"
2
3print(s.strip())   # "Hello World"(去除两端空白)
4print(s.lstrip())  # "Hello World  \n"(去除左侧)
5print(s.rstrip())  # "  Hello World"(去除右侧)

判断方法

1s = "Python123"
2
3print(s.startswith("Py"))  # True
4print(s.endswith("123"))   # True
5print(s.isalpha())         # False(包含数字)
6print(s.isdigit())         # False(不全是数字)
7print(s.isalnum())         # True(字母+数字)
8print("123".isdigit())     # True
9print("abc".isalpha())     # True

5. 字符串的不可变性

字符串是不可变的,不能修改单个字符:

1s = "Python"
2# s[0] = 'J'  # TypeError: 字符串不支持修改
3
4# 必须创建新字符串
5s = 'J' + s[1:]  # "Jython"

为什么不可变

  1. 安全性:字符串常用作字典的键
  2. 性能:可以缓存和优化
  3. 线程安全:多线程环境下更安全

6. 字符串编码

Python 3 中字符串默认是 Unicode:

 1# 编码:str → bytes
 2s = "你好"
 3b = s.encode("utf-8")  # b'\xe4\xbd\xa0\xe5\xa5\xbd'
 4print(type(b))  # <class 'bytes'>
 5
 6# 解码:bytes → str
 7s2 = b.decode("utf-8")  # "你好"
 8
 9# 其他编码
10b_gbk = s.encode("gbk")

7. 正则表达式入门

处理复杂的字符串模式,需要正则表达式:

 1import re
 2
 3# 查找
 4text = "我的电话是13812345678,邮箱是test@example.com"
 5phone = re.search(r"1\d{10}", text)
 6if phone:
 7    print(phone.group())  # 13812345678
 8
 9# 查找所有
10emails = re.findall(r"\w+@\w+\.\w+", text)
11print(emails)  # ['test@example.com']
12
13# 替换
14text = "今天是2024-01-15"
15result = re.sub(r"\d{4}-\d{2}-\d{2}", "某年某月某日", text)
16print(result)  # "今天是某年某月某日"
17
18# 分割
19data = "apple,banana;orange:grape"
20parts = re.split(r"[,;:]", data)
21print(parts)  # ['apple', 'banana', 'orange', 'grape']

常用正则符号

  • .:任意字符
  • \d:数字
  • \w:字母或数字
  • *:0 次或多次
  • +:1 次或多次
  • {n}:恰好 n 次
  • [abc]:a、b 或 c
  • ^:开头
  • $:结尾

8. 实用技巧

技巧 1:字符串模板

1from string import Template
2
3t = Template("$name今年$age岁")
4result = t.substitute(name="赵六", age=32)
5print(result)  # "赵六今年32岁"

技巧 2:多行字符串格式化

 1data = {
 2    "name": "Python",
 3    "version": "3.11",
 4    "year": 2023
 5}
 6
 7info = f"""
 8编程语言:{data['name']}
 9版本:{data['version']}
10发布年份:{data['year']}
11"""
12print(info)

技巧 3:字符串对齐

1# 左对齐
2print("Hello".ljust(10, '*'))  # Hello*****
3
4# 右对齐
5print("Hello".rjust(10, '*'))  # *****Hello
6
7# 居中
8print("Hello".center(10, '*'))  # **Hello***

9. 小结

今天我们深入学习了 Python 字符串:

  • 创建:单引号、双引号、三引号、原始字符串
  • 格式化:%、format()、f-string(推荐)
  • 索引切片:灵活的访问和截取
  • 方法:大小写、查找、替换、分割、连接、判断
  • 不可变性:字符串不能修改
  • 编码:Unicode、UTF-8
  • 正则表达式:处理复杂模式

字符串处理是编程的基本功,熟练掌握这些技巧,能让你的代码更优雅高效。


练习题

  1. 写一个函数,判断一个字符串是否是回文(正读反读都一样,如"上海自来水来自海上")
  2. 使用正则表达式,从一段文本中提取所有的 URL
  3. 写一个程序,统计一段文本中每个单词出现的次数

思考题

为什么 Python 字符串设计成不可变的?这带来了哪些好处和限制?


本文代码示例


相关阅读