一、字符串基础
1. 字符串定义
# 单引号/双引号定义
s1 = 'Hello'
s2 = "World"
s3 = '''多行
字符串''' # 三引号支持换行
# 转义字符
escaped = "He said:\"Python is awesome!\"\nNew line" # \n换行,\"转义引号
raw_str = r"C:\new_folder\test" # 原始字符串(不转义)
2. 索引与切片
s = "Python"
print(s[0]) # 'P'(正向索引,从0开始)
print(s[-1]) # 'n'(负向索引,从-1开始)
print(s[2:5]) # 'tho'(切片含头不含尾)
print(s[::2]) # 'Pto'(步长2)
3. 常用方法
# 分割与连接
s = "apple,banana,orange"
print(s.split(",")) # ['apple', 'banana', 'orange']
print("-".join(["2023", "08", "15"])) # "2023-08-15"
# 大小写转换
print("Hello".lower()) # 'hello'
print("world".upper()) # 'WORLD'
# 去除空格
print(" python ".strip()) # 'python'
print("**text**".strip("*")) # 'text'
# 查找替换
print("abcdcba".count("c")) # 2
print("python".find("th")) # 2(返回索引)
print("hello".replace("l", "x")) # 'hexxo'
二、字符串进阶
1. 字符串格式化
# 旧式格式化
print("%s is %d years old" % ("Alice", 25)) # Alice is 25
# str.format()
print("{0} + {1} = {2}".format(2, 3, 2+3)) # 2 + 3 = 5
# f-string(Python 3.6+)
name = "Bob"
print(f"{name.upper()} has ${1000:,.2f}") # BOB has $1,000.00
# 格式对齐
print(f"{'left':<10}|{'center':^10}|{'right':>10}")
# left | center | right
2. 字符串与编码
# 编码转换
s = "中文"
bytes_data = s.encode("utf-8") # b'\xe4\xb8\xad\xe6\x96\x87'
decoded_str = bytes_data.decode("utf-8") # 中文
# 检查编码
print("ß".isascii()) # False(ASCII范围外)
print("abc".isalpha()) # True(全字母)
3. 正则表达式(需import re)
import re
# 匹配查找
pattern = r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b"
print(bool(re.search(pattern, "test@example.com"))) # True
# 查找所有数字
nums = re.findall(r"\d+", "A1B23C456") # ['1', '23', '456']
# 替换操作
text = re.sub(r"\s+", " ", "Multiple spaces") # "Multiple spaces"
4. 性能优化技巧z
# 避免用 + 拼接大量字符串
# 低效方式
result = ""
for i in range(10000):
result += str(i)
# 高效方式
parts = []
for i in range(10000):
parts.append(str(i))
result = "".join(parts)
# 字符串驻留(小字符串复用)
a = "hello"
b = "hello"
print(a is b) # True(相同id)
三、总结
- 基础重点:掌握索引/切片、常用方法、三种格式化方式
- 进阶技巧:
- 使用f-string进行复杂格式化
- 正则表达式处理复杂文本模式
- 用join()代替+进行大量拼接
- 注意点:
- 字符串不可变性(每次操作生成新对象)
- 处理中文时注意编码问题
- 了解字符串驻留机制(小字符串自动复用)
通过示例代码练习可快速提升字符串处理能力,建议尝试实现以下任务:
- 从文本中提取所有电话号码
- 格式化输出表格数据
- 清洗包含特殊字符的文本数据