Python 教程 07:字符串深入

“语言是思维的外壳。”

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

1. 字符串的创建

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

# 单引号
s1 = 'Hello'

# 双引号
s2 = "World"

# 三引号(多行字符串)
s3 = """这是一个
多行
字符串"""

s4 = '''也可以用
单引号'''

# 原始字符串(忽略转义字符)
path = r"C:\Users\name\documents"  # \n不会被解释为换行

# 字符串拼接
full = s1 + " " + s2  # "Hello World"

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

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

name = "张三"
age = 25
print("我叫%s,今年%d岁" % (name, age))

# 格式控制
pi = 3.14159
print("π = %.2f" % pi)  # 保留2位小数

方法 2:format()方法

# 位置参数
print("{}+{}={}".format(1, 2, 3))

# 索引
print("{0}+{1}={2}".format(1, 2, 3))
print("{2}+{1}={0}".format(3, 2, 1))  # 调换顺序

# 关键字参数
print("{name}今年{age}岁".format(name="李四", age=30))

# 格式控制
print("{:.2f}".format(3.14159))  # 3.14
print("{:0>5}".format(42))      # 00042(左侧填充0,总宽度5)
print("{:*^10}".format("Hi"))   # ****Hi****(居中,宽度10,填充*)

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

name = "王五"
age = 28
city = "北京"

# 简洁直观
print(f"{name}今年{age}岁,来自{city}")

# 表达式
print(f"明年我{age + 1}岁")
print(f"2的10次方是{2 ** 10}")

# 格式控制
pi = 3.14159
print(f"π ≈ {pi:.2f}")

# 对齐和填充
num = 42
print(f"{num:0>5}")   # 00042
print(f"{num:*^10}")  # ****42****

# 调试输出(Python 3.8+)
x = 10
print(f"{x=}")  # x=10

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

3. 字符串索引和切片

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

text = "Python"

# 索引(从0开始)
print(text[0])   # 'P'
print(text[-1])  # 'n'(倒数第一个)
print(text[-2])  # 'o'(倒数第二个)

# 切片 [start:stop:step]
print(text[0:3])   # 'Pyt'(0到2,不含3)
print(text[:3])    # 'Pyt'(省略start默认为0)
print(text[3:])    # 'hon'(省略stop默认到末尾)
print(text[:])     # 'Python'(复制整个字符串)

# 步长
print(text[::2])   # 'Pto'(每隔一个字符)
print(text[::-1])  # 'nohtyP'(反转字符串)

# 负索引切片
print(text[-3:])   # 'hon'(最后3个字符)

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

4. 字符串方法:工具箱

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

大小写转换

s = "Hello World"

print(s.upper())       # 'HELLO WORLD'
print(s.lower())       # 'hello world'
print(s.capitalize())  # 'Hello world'(首字母大写)
print(s.title())       # 'Hello World'(每个单词首字母大写)
print(s.swapcase())    # 'hELLO wORLD'(大小写互换)

查找和替换

s = "Python is awesome, Python is easy"

# 查找
print(s.find("Python"))      # 0(第一次出现的位置)
print(s.find("Java"))        # -1(没找到)
print(s.count("Python"))     # 2(出现次数)

# 替换
print(s.replace("Python", "Go"))  # 全部替换
print(s.replace("Python", "Go", 1))  # 只替换第1个

分割和连接

# 分割
s = "apple,banana,orange"
fruits = s.split(",")  # ['apple', 'banana', 'orange']

s2 = "Hello   World"
words = s2.split()  # ['Hello', 'World'](按空白符分割)

# 连接
fruits = ["apple", "banana", "orange"]
result = ",".join(fruits)  # "apple,banana,orange"

# 分行
text = "第一行\n第二行\n第三行"
lines = text.splitlines()  # ['第一行', '第二行', '第三行']

去除空白

s = "  Hello World  \n"

print(s.strip())   # "Hello World"(去除两端空白)
print(s.lstrip())  # "Hello World  \n"(去除左侧)
print(s.rstrip())  # "  Hello World"(去除右侧)

判断方法

s = "Python123"

print(s.startswith("Py"))  # True
print(s.endswith("123"))   # True
print(s.isalpha())         # False(包含数字)
print(s.isdigit())         # False(不全是数字)
print(s.isalnum())         # True(字母+数字)
print("123".isdigit())     # True
print("abc".isalpha())     # True

5. 字符串的不可变性

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

s = "Python"
# s[0] = 'J'  # TypeError: 字符串不支持修改

# 必须创建新字符串
s = 'J' + s[1:]  # "Jython"

为什么不可变

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

6. 字符串编码

Python 3 中字符串默认是 Unicode:

# 编码:str → bytes
s = "你好"
b = s.encode("utf-8")  # b'\xe4\xbd\xa0\xe5\xa5\xbd'
print(type(b))  # <class 'bytes'>

# 解码:bytes → str
s2 = b.decode("utf-8")  # "你好"

# 其他编码
b_gbk = s.encode("gbk")

7. 正则表达式入门

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

import re

# 查找
text = "我的电话是13812345678,邮箱是test@example.com"
phone = re.search(r"1\d{10}", text)
if phone:
    print(phone.group())  # 13812345678

# 查找所有
emails = re.findall(r"\w+@\w+\.\w+", text)
print(emails)  # ['test@example.com']

# 替换
text = "今天是2024-01-15"
result = re.sub(r"\d{4}-\d{2}-\d{2}", "某年某月某日", text)
print(result)  # "今天是某年某月某日"

# 分割
data = "apple,banana;orange:grape"
parts = re.split(r"[,;:]", data)
print(parts)  # ['apple', 'banana', 'orange', 'grape']

常用正则符号

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

8. 实用技巧

技巧 1:字符串模板

from string import Template

t = Template("$name今年$age岁")
result = t.substitute(name="赵六", age=32)
print(result)  # "赵六今年32岁"

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

data = {
    "name": "Python",
    "version": "3.11",
    "year": 2023
}

info = f"""
编程语言:{data['name']}
版本:{data['version']}
发布年份:{data['year']}
"""
print(info)

技巧 3:字符串对齐

# 左对齐
print("Hello".ljust(10, '*'))  # Hello*****

# 右对齐
print("Hello".rjust(10, '*'))  # *****Hello

# 居中
print("Hello".center(10, '*'))  # **Hello***

9. 小结

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

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

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


练习题

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

思考题

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


本文代码示例


相关阅读