上一篇
Python字符串操作完全指南 - 从基础到高级技巧
- Python
- 2025-07-23
- 790
Python字符串操作完全指南
掌握Python字符串核心操作,提升编程效率
Python字符串基础操作
创建与访问
# 创建字符串
s1 = 'Hello, World!'
s2 = "Python Programming"
s3 = '''多行
字符串示例'''
# 访问字符
print(s1[0]) # H
print(s1[-1]) # !
切片操作
s = "Python is amazing!"
# 基本切片
print(s[0:6]) # Python
print(s[7:9]) # is
# 使用步长
print(s[0:12:2]) # Pto sa
# 反向切片
print(s[::-1]) # !gnizama si nohtyP
拼接与重复
# 字符串拼接
s1 = "Hello"
s2 = "World"
print(s1 + ", " + s2 + "!") # Hello, World!
# 字符串重复
print("Ha" * 3) # HaHaHa
# join方法高效拼接
words = ["Python", "is", "powerful"]
print(" ".join(words)) # Python is powerful
字符串格式化方法
1. % 格式化
name = "Alice"
age = 30
print("Name: %s, Age: %d" % (name, age))
2. str.format()
print("Name: {0}, Age: {1}. {0} is a programmer".format(name, age))
3. f-strings (Python 3.6+)
print(f"Name: {name}, Age: {age}. Next year: {age+1}")
常用字符串方法
大小写转换
"hello".upper() # "HELLO"
"WORLD".lower() # "world"
"python guide".title() # "Python Guide"
查找与替换
"Python is fun".find('is') # 7
"Python is fun".index('fun') # 10
"Hello World".replace('World', 'Python')
分割与连接
"apple,banana,cherry".split(',')
# ['apple', 'banana', 'cherry']
"-".join(['2023', '08', '01'])
# "2023-08-01"
去除空白
" python ".strip() # "python"
" python ".lstrip() # "python "
" python ".rstrip() # " python"
正则表达式应用
import re
# 查找匹配
text = "Contact: email@example.com, phone: 123-456-7890"
emails = re.findall(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', text)
# ['email@example.com']
# 替换字符串
new_text = re.sub(r'\d{3}-\d{3}-\d{4}', '[PHONE]', text)
# "Contact: email@example.com, phone: [PHONE]"
# 分割字符串
re.split(r'[,:]\s*', text)
# ['Contact', 'email@example.com', 'phone', '123-456-7890']
字符串编码与字节转换
# 字符串转字节
s = "Python编程"
b = s.encode('utf-8') # b'Python\xe7\xbc\x96\xe7\xa8\x8b'
# 字节转字符串
b.decode('utf-8') # "Python编程"
# 处理不同编码
with open('file.txt', 'r', encoding='utf-8') as f:
content = f.read()
本文由GanWen于2025-07-23发表在吾爱品聚,如有疑问,请联系我们。
本文链接:https://www.521pj.cn/20256327.html
发表评论