10.1 字符串的基本概念 #
str 表示文本,是不可变序列:修改、拼接、替换都会得到新字符串,原串不变。
s1 = "双引号"
s2 = '单引号'
s3 = """多行
文本"""
print(len(s3)) # 字符个数
print(type(s1)) # <class 'str'>常用转义:\n 换行、\t 制表符、\" 引号。
正则、Windows 路径建议用原始字符串,反斜杠不转义
在 Python 中,字符串前面的 r 表示原始字符串(raw string)。它的作用是告诉 Python 不要将字符串中的反斜杠 \ 解释为转义字符的起始符,而是按字面原样保留。
path = r"C:\Users\data\new.txt"10.2 索引与切片 #
text = "Hello Python"
print(text[0]) # H
print(text[-1]) # n(最后一个)
print(text[0:5]) # Hello
print(text[6:]) # Python10.3 常用方法 #
项目里高频使用的字符串方法:
| 方法 | 用途 |
|---|---|
strip() |
去掉首尾空白(表单、CSV 很常见) |
lower() / upper() |
大小写转换(比较、规范化) |
split(sep) |
按分隔符拆成列表 |
join(iterable) |
用分隔符连接列表为字符串 |
replace(old, new) |
替换子串 |
startswith() / endswith() |
判断前缀/后缀(URL、文件名) |
in |
判断是否包含子串 |
email = " User@Example.COM "
print(email.strip().lower()) # user@example.com
csv = "apple,banana,orange"
fruits = csv.split(",") # ['apple', 'banana', 'orange']
print(", ".join(fruits)) # apple, banana, orange
url = "https://api.example.com/users"
print(url.startswith("https")) # True
filename = "report.pdf"
print(filename.endswith(".pdf")) # True
msg = "操作成功"
print("成功" in msg) # True查找与替换:
text = "Hello World"
print(text.find("World")) # 6,找不到返回 -1
print(text.replace("World", "Python")) # Hello Python10.4 字符串格式化 #
拼接变量优先用 f-string:
name = "Alice"
age = 25
print(f"用户: {name}, 年龄: {age}")
print(f"明年: {age + 1}")10.5 编码 #
字符串在内存中是 Unicode 文本;写入文件或发网络前需 encode("utf-8") 得到 bytes。
b = "你好".encode("utf-8")
print(b.decode("utf-8")) # 你好10.6 项目开发要点 #
- 不可变:不能写
s[0] = "x";用s = s.replace(...)或拼接得到新串 - 大量拼接用
join:循环里避免result += item,应"".join(parts) - 用户输入先
strip():避免首尾空格导致校验失败 - 比较邮箱、用户名:常配合
.lower()做不区分大小写比较 - 解析简单 CSV/日志:
split(",")够用;复杂格式用csv模块 - 格式化只用 f-string