第六篇:字符串详解——转义、多行与原始字符串完全指南
前言
字符串是编程中使用最频繁的数据类型之一。无论处理用户输入、文件读取还是 API 响应,都离不开字符串操作。本文将全面讲解 Python 字符串的各种表示方式:单引号与双引号的选择、转义字符的使用、多行字符串的写法、原始字符串处理特殊字符的技巧,以及空值 None 的概念。
字符串的基础表示
Python 提供了多种方式来定义字符串,理解它们的区别有助于写出更清晰的代码。
单引号 vs 双引号
Python 中单引号和双引号定义的字符串完全等价,可以根据需要选择:
# 单引号
name1 = '小明'
name2 = "小红"
print(type(name1)) # <class 'str'>
# 何时用哪种?
# 如果字符串内部包含单引号,使用双引号
say_hello = "Hello, World!"
print(say_hello)
# 如果字符串内部包含双引号,使用单引号
say_hi = 'He said "Hi"'
print(say_hi) # He said "Hi"
三引号字符串
三引号可用于多行文本和文档字符串:
poem = """床前明月光,
疑是地上霜。
举头望明月,
低头思故乡。"""
print(poem)
def greet(name):
"""向用户提供问候。
参数:
name (str): 用户名
返回:
str: 问候消息
"""
return f"你好,{name}!"
转义字符
转义字符以反斜杠 \ 开头,用于表示无法直接输入的字符。
常用转义序列
| 转义序列 | 含义 | 示例 |
|---|---|---|
\n |
换行 | "第一行\n第二行" |
\t |
制表符 | "姓名\t年龄" |
\\ |
反斜杠本身 | C:\\Users\\Admin |
\' |
单引号 | 'It\'s a day' |
\" |
双引号 | "She said \"Hi\"" |
# 换行
text = "第一行\n第二行\n第三行"
print(text)
# 制表符对齐
print("姓名\t年龄\t城市")
print("张三\t25\t北京")
# 文件路径
path = "C:\\Users\\Admin\\Documents\\file.txt"
print(path) # C:\Users\Admin\Documents\file.txt
⚠️ 常见陷阱
# 错误:忘记对反斜杠转义
path = "C:\new\folder" # \n 被解释为换行符!
# 正确方式一:双重转义
path = "C:\\new\\folder"
# 正确方式二:原始字符串(推荐)
path = r"C:\new\folder"
原始字符串
原始字符串以 r 或 R 开头,不会对任何字符进行转义。
基本用法
# Windows 路径
path = r"C:\new\folder\file.txt"
print(path) # C:\new\folder\file.txt ← 完整保留反斜杠
# 正则表达式(大量反斜杠的场景)
import re
pattern = r"\d{3}-\d{4}" # 匹配手机号格式
print(pattern) # \d{3}-\d{4}
text = "我的电话是 123-4567"
match = re.search(pattern, text)
if match:
print(f"找到匹配:{match.group()}")
# 输出:找到匹配:123-4567
注意事项
# ❌ 原始字符串不能以奇数个反斜杠结尾
bad = r"C:\new\" # SyntaxError!
# ✅ 解决方法
good = "C:\new\\"
also_good = r"C:\new" + "\\"
多行字符串
三引号(最常用)
long_text = """这是一段很长的文本。
可以自然地跨越多行,
非常适合描述段落或诗歌。"""
join() 方法高效拼接
words = ["Python", "is", "awesome"]
result = " ".join(words)
print(result) # Python is awesome
# 实际用途:格式化表格数据
headers = ["姓名", "年龄", "城市"]
separator = " | ".join(headers)
print(separator) # 姓名 | 年龄 | 城市
字符串不可变性
Python 中的字符串是不可变的——一旦创建就不能修改。
greeting = "Hello"
# greeting[0] = "J" # ❌ TypeError!
greeting = "J" + greeting[1:]
print(greeting) # Jello
# 好处:线程安全、支持哈希化、节省内存
常用字符串方法速查
大小写转换
text = "Hello, World!"
print(text.upper()) # HELLO, WORLD!
print(text.lower()) # hello, world!
print(text.title()) # Hello, World!
print(text.swapcase()) # hELLO, wORLD!
搜索与替换
text = "Python is great. I love Python."
print(text.find("Python")) # 0 — 首次出现位置
print(text.rfind("Python")) # 20 — 最后一次
print("xyz" in text) # False
print(text.count("Python")) # 2
replaced = text.replace("Python", "Java")
print(replaced) # Java is great. I love Java.
# 限制替换次数
replaced_once = text.replace("Python", "Java", 1)
print(replaced_once) # Java is great. I love Python.
去除空白
text = " Hello, World! "
print(text.strip()) # "Hello, World!"
print(text.lstrip()) # "Hello, World! "
print(text.rstrip()) # " Hello, World!"
filename = "***important***.txt"
clean_name = filename.strip("*")
print(clean_name) # important***.txt
分割与连接
csv_data = "张三,25,北京;李四,30,上海"
names = csv_data.split(";")
print(names) # ['张三,25,北京', '李四,30,上海']
first_person = names[0].split(",")
print(first_person) # ['张三', '25', '北京']
# splitlines
multiline = "Line 1\nLine 2\r\nLine 3"
lines = multiline.splitlines()
print(lines) # ['Line 1', 'Line 2', 'Line 3']
判断方法
print("123".isdigit()) # True
print("abc".isalpha()) # True
print("abc123".isalnum()) # True
print(" ".isspace()) # True
print("hello.pdf".endswith(".pdf")) # True
填充与对齐
code = "A001"
print(code.center(10, "=")) # ===A001===
print(code.ljust(10, "-")) # A001--------
print(code.rjust(10, "0")) # 0000000A01
空值 None
None 是 Python 的特殊常量,表示"没有值"。
result = None
print(result) # None
print(type(result)) # <class 'NoneType'>
# 用 is None 而不是 == None
print(None is None) # True — 推荐使用 is
value = None
if value:
print("有值")
else:
print("无值 — None 被视为 False")
实战练习
密码强度检测器
def check_password_strength(password):
issues = []
if len(password) < 8:
issues.append("密码长度不足 8 位")
if not any(c.isupper() for c in password):
issues.append("缺少大写字母")
if not any(c.islower() for c in password):
issues.append("缺少小写字母")
if not any(c.isdigit() for c in password):
issues.append("缺少数字")
if not any(not c.isalnum() for c in password):
issues.append("缺少特殊字符")
if issues:
return f"弱密码,建议修复:{';'.join(issues)}"
else:
return "强密码 ✅"
URL 解析器
def parse_url(url):
result = {}
if "://" in url:
result["protocol"], url = url.split("://", 1)
if "/" in url:
result["host"], path = url.split("/", 1)
result["path"] = "/" + path
else:
result["host"] = url
return result
文本格式化报告生成器
def format_report(title, lines):
max_len = max(len(line) for line in [title] + lines) + 4
width = max(max_len, 40)
border = "+" + "-" * width + "+"
result = [border, "| " + title.center(width - 4) + " |", border]
for line in lines:
result.append("| " + line.center(width - 4) + " |")
result.append(border)
return "\n".join(result)
总结
本文涵盖了 Python 字符串的核心知识点:
- 基本表示 — 单引号、双引号、三引号的不同用途
- 转义字符 —
\n、\t、\\等及常见陷阱 - 原始字符串 — 使用
r前缀避免转义问题 - 多行字符串 — 三引号、隐式行连接、join() 高效拼接
- 不可变性 — 字符串创建后不可修改的特性
- 常用方法 — upper/lower、find/index、replace、split/join 等
- 空值 None — 特殊"无值"状态,用
is None判断
下一篇文章将深入讲解变量与常量:动态类型机制、赋值语句本质。
本文是 Python 教程系列的第六篇。
