首页 › Python 3 教程 › 字符串详解
字符串详解
字符串是 Python 中使用最频繁的类型之一。本节系统地介绍字符串的创建、索引、切片、常用方法和格式化。
创建字符串
单引号和双引号完全等价,三引号可以跨多行:
s1 = 'hello'
s2 = "it's ok"
s3 = """第一行
第二行"""
path = r"C:\new\table" # 原始字符串,反斜杠不转义
print(s2, path)
转义字符
| 写法 | 含义 |
|---|---|
\n | 换行 |
\t | 制表符 |
\\ | 反斜杠本身 |
\' \" | 引号 |
\u4e2d | Unicode 字符(中) |
索引与切片
字符串可以看成字符的序列,下标从 0 开始,负数表示从末尾倒数:
s = "Python3"
print(s[0], s[-1]) # P 3
print(s[0:2]) # Py
print(s[2:]) # thon3
print(s[:-1]) # Python
print(s[::2]) # Pto3
print(s[::-1]) # 3nohtyP
切片的格式是 [start:stop:step],包含 start 不包含 stop,任何一项都可以省略。切片越界不会报错,只会返回能取到的部分。
字符串是不可变的
s = "hello"
# s[0] = "H" # TypeError: 'str' object does not support item assignment
s = "H" + s[1:] # 只能创建新字符串
print(s)
拼接与重复
print("Py" + "thon")
print("=" * 20)
words = ["Python", "is", "fun"]
print(" ".join(words)) # 大量拼接时用 join,比 + 效率高
查找与判断
s = "hello python, hello world"
print("python" in s) # True
print(s.find("hello")) # 0
print(s.find("hello", 1)) # 14
print(s.count("hello")) # 2
print(s.startswith("hello"), s.endswith("!"))
拆分与清理
line = " name, age , city \n"
fields = [f.strip() for f in line.split(",")]
print(fields) # ['name', 'age', 'city']
完整示例:格式化名片
name, title, phone = "张小明", "Python 开发工程师", "13800001234"
width = 30
print("+" + "-" * width + "+")
print("|" + name.center(width - 2) + " |")
print("|" + title.center(width - 5) + " |")
masked = phone[:3] + "****" + phone[-4:]
print("|" + f"电话:{masked}".center(width - 3) + " |")
print("+" + "-" * width + "+")
小结:字符串的方法都不会修改原字符串,而是返回新字符串。记不住方法名时,可以在交互式解释器中输入dir(str)或help(str.split)查看。完整的方法列表见参考手册中的"字符串方法"。
练习题
学完本节后,试着独立完成下面的练习,再展开参考答案对照。
练习 1 给定文件名 "report_2026_final.PDF",分别取出不带扩展名的文件名和小写的扩展名。
查看参考答案
name = "report_2026_final.PDF"
stem, _, ext = name.rpartition(".")
print(stem, ext.lower())参考输出:
report_2026_final pdf练习 2 把手机号 13812345678 中间四位替换为 ****。
查看参考答案
phone = "13812345678"
print(phone[:3] + "****" + phone[7:])参考输出:
138****5678练习 3 统计字符串 "Hello World Python" 中大写字母的个数。
查看参考答案
s = "Hello World Python"
print(sum(1 for c in s if c.isupper()))参考输出:
3