【Python 字符串】
Python 中的字符串(str
)是用于处理文本数据的基础类型,具有不可变性、丰富的内置方法和灵活的操作方式。以下是 Python 字符串的核心知识点:
一、基础特性
-
定义方式:
s1 = '单引号字符串' s2 = "双引号字符串" s3 = '''三引号多行 字符串''' s4 = """三引号多行 字符串"""
-
不可变性:
s = "hello" s[0] = 'H' # 报错:字符串不可修改
-
转义字符:
path = 'C:\\Users\\Name\\Documents' # 反斜杠需转义 text = "他说:\"Python 很有趣!\"" # 双引号需转义
二、常用操作
1. 字符串拼接
name = "Alice"
greeting = "Hello, " + name + "!" # 拼接 → "Hello, Alice!"
2. 字符串重复
"Hi" * 3 # → "HiHiHi"
3. 成员检查
"a" in "apple" # → True
4. 索引与切片
s = "Python"
s[0] # → 'P'(正向索引,从0开始)
s[-1] # → 'n'(反向索引,从-1开始)
s[1:4] # → 'yth'(切片,左闭右开)
s[::-1] # → 'nohtyP'(逆序)
三、常用方法
1. 大小写转换
s = "hello World"
s.upper() # → "HELLO WORLD"
s.lower() # → "hello world"
s.title() # → "Hello World"
2. 搜索与统计
s = "apple banana apple"
s.find("apple") # → 0(首次出现位置)
s.count("apple") # → 2(出现次数)
s.startswith("ap") # → True
3. 替换与分割
s = "a,b,c,d"
s.replace(",", "-") # → "a-b-c-d"
s.split(",") # → ["a", "b", "c", "d"]
"-".join(["a", "b"]) # → "a-b"
4. 去除空白
s = " hello \n"
s.strip() # → "hello"(去除首尾空白)
s.lstrip() # → "hello \n"(仅左侧)
s.rstrip() # → " hello"(仅右侧)
四、字符串格式化
1. f-string(推荐)
name = "Alice"
age = 25
f"姓名:{name},年龄:{age}" # → "姓名:Alice,年龄:25"
2. str.format()
"{} is {} years old".format(name, age) # → "Alice is 25 years old"
3. 百分号格式化
"数值:%.2f" % 3.1415 # → "数值:3.14"
五、编码处理
1. 编码转换
s = "你好"
bytes_data = s.encode("utf-8") # → 字节串 b'\xe4\xbd\xa0\xe5\xa5\xbd'
original = bytes_data.decode("utf-8") # → "你好"
2. 处理常见错误
# 忽略无法解码的字符
s = b'\xe4\xbd\xa0\xff'.decode("utf-8", errors="ignore") # → "你"
六、高级技巧
1. 格式化对齐
s = "42"
s.rjust(5, '0') # → "00042"(右对齐,填充0)
s.center(7, '-') # → "--42---"
2. 模板字符串(安全场景)
from string import Template
tpl = Template("Hello, $name!")
tpl.substitute(name="Bob") # → "Hello, Bob!"
3. 路径操作(pathlib
模块)
from pathlib import Path
path = Path("/user/docs/file.txt")
path.stem # → "file"
path.suffix # → ".txt"
七、性能优化
-
避免频繁拼接:
# 低效方式 res = "" for c in "long string":res += c# 高效方式 parts = [] for c in "long string":parts.append(c) "".join(parts)
-
预编译正则表达式(如需频繁匹配):
import re pattern = re.compile(r"\d+") pattern.findall("a1b22c333") # → ['1', '22', '333']
八、常见陷阱
-
索引越界:
s = "abc" s[3] # 报错:IndexError
-
编码不一致:
# 错误示例:混合编码可能导致乱码 with open("file.txt", "w", encoding="gbk") as f:f.write("你好") # 需确保读写编码一致
通过掌握这些内容,可以高效处理文本数据,从简单的日志解析到复杂的自然语言处理任务。实际应用中需根据场景选择合适的方法,并注意编码和性能问题。