目录
前言
字符串是Python中最常用的数据类型之一,掌握字符串操作对于编写高效、优雅的Python代码至关重要。本文将从基础操作到高级技巧,全面介绍Python字符串的各种用法,并配以丰富的示例代码。
1. 字符串基础操作
1.1 创建字符串
# 单引号
single_quote = 'Hello, Python!'
# 双引号
double_quote = "Hello, Python!"
# 三引号(多行字符串)
multi_line = """这是
一个
多行字符串"""
# 空字符串
empty_str = ""
1.2 字符串连接
# 使用+运算符
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2 # "Hello World"
# 使用join()方法(推荐用于多个字符串)
words = ["Python", "is", "awesome"]
sentence = " ".join(words) # "Python is awesome"
# 使用f-string(Python 3.6+)
name = "Alice"
greeting = f"Hello, {name}!" # "Hello, Alice!"
2. 字符串格式化
2.1 传统格式化方法
# %格式化
name = "Bob"
age = 25
info = "My name is %s and I'm %d years old." % (name, age)
# format()方法
info = "My name is {} and I'm {} years old.".format(name, age)
info = "My name is {name} and I'm {age} years old.".format(name=name, age=age)
2.2 f-string
name = "Charlie"
age = 30
height = 1.75
# 基本用法
info = f"Name: {name}, Age: {age}"
# 表达式
info = f"Next year, {name} will be {age + 1} years old."
# 格式化数字
pi = 3.1415926
formatted_pi = f"Pi: {pi:.2f}" # "Pi: 3.14"
# 对齐和填充
table = f"| {name:<10} | {age:>5} | {height:^10.2f} |"
3. 字符串常用方法
3.1 大小写转换
text = "Python Programming"
print(text.upper()) # "PYTHON PROGRAMMING"
print(text.lower()) # "python programming"
print(text.title()) # "Python Programming"
print(text.capitalize()) # "Python programming"
print(text.swapcase()) # "pYTHON pROGRAMMING"
3.2 查找和替换
text = "The quick brown fox jumps over the lazy dog"
# 查找
print(text.find("fox")) # 16 (返回索引,找不到返回-1)
print(text.index("fox")) # 16 (返回索引,找不到抛出异常)
print(text.count("o")) # 4 (计数)
# 替换
print(text.replace("fox", "cat"))
print(text.replace("o", "O", 2)) # 只替换前2个
3.3 分割和连接
# split()方法
csv_data = "apple,banana,orange"
fruits = csv_data.split(",") # ['apple', 'banana', 'orange']
# 指定分割次数
text = "one:two:three:four"
parts = text.split(":", 2) # ['one', 'two', 'three:four']
# rsplit() - 从右侧开始分割
parts = text.rsplit(":", 1) # ['one:two:three', 'four']
# partition() - 只分割一次,返回三元组
text = "name@example.com"
username, sep, domain = text.partition("@")
3.4 去除空白字符
text = " hello world \n"
print(text.strip()) # "hello world" (去除两端)
print(text.lstrip()) # "hello world \n" (去除左侧)
print(text.rstrip()) # " hello world" (去除右侧)
# 去除指定字符
text = ">>>hello<<<"
print(text.strip("><")) # "hello"
4. 字符串判断方法
text = "Python3"
print(text.isalpha()) # False (包含数字)
print(text.isdigit()) # False
print(text.isalnum()) # True (字母和数字)
print(text.islower()) # False
print(text.isupper()) # False
print(text.istitle()) # True (首字母大写)
print(text.isspace()) # False
# 实用的判断方法
filename = "document.pdf"
print(filename.endswith(".pdf")) # True
print(filename.startswith("doc")) # True
5. 高级字符串操作
5.1 字符串翻译
# 创建翻译表
text = "Hello, World!"
trans_table = str.maketrans("HW", "JC", "!") # 将H→J, W→C, 删除!
result = text.translate(trans_table) # "Jello, Cold"
5.2 字符串填充
text = "Python"
# 居中对齐
print(text.center(20, "*")) # "*******Python*******"
# 左对齐
print(text.ljust(20, "-")) # "Python--------------"
# 右对齐
print(text.rjust(20, ">")) # ">>>>>>>>>>>>>>Python"
5.3 字符串编码和解码
text = "你好,世界"
# 编码
encoded = text.encode("utf-8")
print(encoded) # b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe4\xb8\x96\xe7\x95\x8c'
# 解码
decoded = encoded.decode("utf-8")
print(decoded) # "你好,世界"
6. 字符串性能优化技巧
6.1 使用join()而不是+连接多个字符串
# 不推荐
result = ""
for s in list_of_strings:
result += s # 每次都会创建新字符串
# 推荐
result = "".join(list_of_strings) # 只分配一次内存
6.2 使用列表收集结果,最后join
# 构建HTML
parts = ["<html>"]
for item in items:
parts.append(f"<li>{item}</li>")
parts.append("</html>")
html = "".join(parts)
总结
Python的字符串操作功能强大且灵活,掌握这些技巧可以大大提高代码质量和开发效率。本文涵盖了从基础到高级的字符串操作,希望对你的Python编程之路有所帮助。
记住,编写好的字符串处理代码不仅要功能正确,还要考虑性能和可读性。在实际项目中,根据具体需求选择最合适的方法。
1214

被折叠的 条评论
为什么被折叠?



