上一篇
Python字符串完全指南:从基础到高级操作 | Python编程教程
- Python
- 2025-07-28
- 39
Python字符串完全指南:从基础到高级操作
全面掌握Python字符串操作的核心方法与实用技巧
Python字符串基础
在Python中,字符串是不可变的Unicode字符序列,可以使用单引号(' ')、双引号(" ")或三引号(''' '''或""" """)创建。
# 字符串定义示例
str1 = '单引号字符串'
str2 = "双引号字符串"
str3 = '''多行
字符串'''
str4 = """另一个多行
字符串示例"""
字符串基础特性
- 不可变性:字符串创建后不能修改,任何修改操作都会创建新字符串
- 索引访问:使用[index]访问单个字符
- 切片操作:使用[start:end:step]获取子串
字符串常用操作
拼接与重复
# 字符串拼接
first = "Hello"
last = "World"
full = first + " " + last # "Hello World"
# 字符串重复
stars = "*" * 10 # "**********"
索引与切片
s = "Python Programming"
# 索引访问
print(s[0]) # 'P'
print(s[-1]) # 'g'
# 切片操作
print(s[0:6]) # "Python"
print(s[7:]) # "Programming"
print(s[::-1]) # 反转字符串
常用字符串方法
方法 | 描述 | 示例 |
---|---|---|
str.lower() | 转换为小写 | "HELLO".lower() → "hello" |
str.upper() | 转换为大写 | "hello".upper() → "HELLO" |
str.strip() | 去除两端空白 | " text ".strip() → "text" |
str.split() | 分割字符串 | "a,b,c".split(",") → ["a","b","c"] |
str.join() | 连接字符串序列 | ",".join(["a","b","c"]) → "a,b,c" |
str.replace() | 替换子串 | "hello".replace("l", "x") → "hexxo" |
str.find() | 查找子串位置 | "python".find("th") → 2 |
str.startswith() | 检查前缀 | "hello".startswith("he") → True |
str.endswith() | 检查后缀 | "world".endswith("ld") → True |
str.isdigit() | 检查是否全数字 | "123".isdigit() → True |
字符串格式化
三种主要格式化方法比较
% 格式化
name = "Alice"
age = 30
text = "Name: %s, Age: %d" % (name, age)
str.format()
name = "Bob"
score = 95.5
text = "Student: {0}, Score: {1:.1f}".format(name, score)
f-string (Python 3.6+)
product = "Laptop"
price = 1299.99
text = f"{product}: ${price:.2f}"
专业提示: Python 3.6+ 中推荐使用f-string,它更简洁、可读性更高且执行效率更好。
字符串编码与字节转换
Python 3中字符串默认使用Unicode,需要显式编码为字节串才能在网络中传输或存储到文件。
# 字符串编码为字节
text = "Python编程"
byte_data = text.encode("utf-8") # b'Python\xe7\xbc\x96\xe7\xa8\x8b'
# 字节解码为字符串
decoded_text = byte_data.decode("utf-8") # "Python编程"
注意: 处理文件时建议明确指定编码:
# 写入文件
with open("file.txt", "w", encoding="utf-8") as f:
f.write("文本内容")
# 读取文件
with open("file.txt", "r", encoding="utf-8") as f:
content = f.read()
高级字符串技巧
原始字符串
处理正则表达式或Windows路径时非常有用
path = r"C:\new_folder\file.txt"
regex = r"\d+\.\d+"
多行字符串
使用三引号创建包含换行的字符串
html = """
<html>
<body>
<h1>标题</h1>
</body>
</html>
"""
性能优化建议
- 避免在循环中使用+拼接字符串 - 使用join()代替
- 频繁字符串操作考虑使用io.StringIO
- 格式化字符串优先选择f-string
- 使用字符串方法而非正则表达式完成简单任务
# 低效做法
result = ""
for s in string_list:
result += s
# 高效做法
result = "".join(string_list)
最佳实践: 对于复杂的字符串解析任务,Python的标准库提供了强大的工具:
- 文本处理:re (正则表达式)
- 字符串模板:string.Template
- 自然语言处理:nltk 库
本文由ZangWu于2025-07-28发表在吾爱品聚,如有疑问,请联系我们。
本文链接:https://521pj.cn/20256728.html
发表评论