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