字符串操作
常用字符串方法
Python提供了许多用于字符串操作的内置方法:
## 大小写转换
text = "labex python course"
print(text.upper()) ## 'LABEX PYTHON COURSE'
print(text.title()) ## 'Labex Python Course'
print(text.capitalize()) ## 'Labex python course'
字符串搜索与检查
text = "LabEx Python Programming"
## 搜索方法
print(text.startswith("LabEx")) ## True
print(text.endswith("Programming")) ## True
print(text.find("Python")) ## 6 (子字符串的索引)
字符串清理与格式化
## 空白处理
messy_text = " LabEx Python "
print(messy_text.strip()) ## 'LabEx Python'
print(messy_text.lstrip()) ## 'LabEx Python '
print(messy_text.rstrip()) ## ' LabEx Python'
字符串替换与分割
## 替换与分割
text = "LabEx,Python,Course"
print(text.replace(",", " ")) ## 'LabEx Python Course'
print(text.split(",")) ## ['LabEx', 'Python', 'Course']
字符串格式化技术
## Format方法
name = "LabEx"
version = 3.8
formatted = "平台: {} 版本: {:.1f}".format(name, version)
print(formatted) ## '平台: LabEx 版本: 3.8'
## F字符串(Python 3.6+)
formatted_f = f"平台: {name} 版本: {version:.1f}"
print(formatted_f) ## '平台: LabEx 版本: 3.8'
字符串操作工作流程
graph TD
A[原始字符串] --> B{操作方法}
B --> C[大写]
B --> D[小写]
B --> E[替换]
B --> F[分割]
高级字符串方法
方法 |
描述 |
示例 |
join() |
连接列表元素 |
"-".join(['LabEx', 'Python']) |
count() |
计算子字符串出现次数 |
"hello".count('l') |
isalnum() |
检查是否为字母数字 |
"LabEx2023".isalnum() |
性能考量
在执行多个字符串操作时,考虑使用列表推导式或生成器表达式以获得更好的性能,特别是处理大型字符串时。
## 高效字符串处理
words = ["LabEx", "Python", "Course"]
processed = [word.upper() for word in words]
字符串操作中的错误处理
try:
result = "LabEx".index("X")
except ValueError:
print("子字符串未找到")