在Python中,字符串处理是日常编程中经常会遇到的操作。Python提供了丰富的内置方法和库来处理字符串,下面介绍一些常用的字符串处理操作和技巧。
1. 字符串基本操作
创建字符串
s1 = 'Hello'
s2 = "World"
s3 = """这是一个多行字符串
可以包含多个行
"""
字符串拼接
# 使用 + 操作符
result = s1 + ' ' + s2 # 输出: Hello World
# 使用 join 方法(推荐用于大量字符串拼接)
words = ['Hello', 'World', '!']
result = ' '.join(words) # 输出: Hello World !
字符串重复
s = 'a' * 5 # 输出: aaaaa
字符串索引和切片
s = "HelloWorld"
print(s[0]) # 输出: H(索引从0开始)
print(s[-1]) # 输出: d(负数索引表示从后往前)
print(s[1:5]) # 输出: ello(切片操作,左闭右开)
print(s[6:]) # 输出: World(从索引6到末尾)
print(s[::-1]) # 输出: dlroWolleH(反转字符串)
2. 常用字符串方法
大小写转换
s = "Hello World"
print(s.upper()) # 输出: HELLO WORLD
print(s.lower()) # 输出: hello world
print(s.title()) # 输出: Hello World(每个单词首字母大写)
print(s.capitalize()) # 输出: Hello world(句子首字母大写)
查找和替换
s = "Hello World"
print(s.find('World')) # 输出: 6(找到返回起始索引)
print(s.find('Python')) # 输出: -1(未找到返回-1)
print(s.index('World')) # 输出: 6(与find类似,但未找到会抛出异常)
print(s.replace('World', 'Python')) # 输出: Hello Python
去除空白字符
s = " Hello World "
print(s.strip()) # 输出: Hello World(去除两端空白字符)
print(s.lstrip()) # 输出: Hello World (去除左侧空白字符)
print(s.rstrip()) # 输出: Hello World(去除右侧空白字符)
分割和连接
s = "Hello,World,Python"
print(s.split(',')) # 输出: ['Hello', 'World', 'Python'](按逗号分割)
s = "Hello\nWorld\nPython"
print(s.splitlines()) # 输出: ['Hello', 'World', 'Python'](按行分割)
words = ['Hello', 'World', 'Python']
print('-'.join(words)) # 输出: Hello-World-Python(用连字符连接)
判断字符串特性
s = "Hello"
print(s.isalpha()) # 输出: True(是否全是字母)
print(s.isdigit()) # 输出: False(是否全是数字)
print(s.islower()) # 输出: False(是否全是小写)
print(s.isupper()) # 输出: False(是否全是大写)
print(s.startswith('He')) # 输出: True(是否以'He'开头)
print(s.endswith('lo')) # 输出: True(是否以'lo'结尾)
3. 字符串格式化
传统格式化(% 操作符)
name = "Alice"
age = 25
print("我的名字是 %s,年龄是 %d" % (name, age)) # 输出: 我的名字是 Alice,年龄是 25
新格式化(str.format())
print("我的名字是 {}, 年龄是 {}".format(name, age)) # 输出: 我的名字是 Alice,年龄是 25
print("我的名字是 {1}, 年龄是 {0}".format(age, name)) # 输出: 我的名字是 Alice,年龄是 25
print("我的名字是 {name}, 年龄是 {age}".format(name=name, age=age)) # 输出: 我的名字是 Alice,年龄是 25
f-strings(Python 3.6+)
print(f"我的名字是 {name}, 年龄是 {age}") # 输出: 我的名字是 Alice,年龄是 25
print(f"2 + 3 = {2 + 3}") # 输出: 2 + 3 = 5
print(f"名字的长度是 {len(name)}") # 输出: 名字的长度是 5
4. 正则表达式处理(re模块)
import re
# 匹配邮箱地址
text = "我的邮箱是 test@example.com,请联系我"
pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
match = re.search(pattern, text)
if match:
print(match.group()) # 输出: test@example.com
# 替换所有数字
text = "今天是2023年5月28日"
new_text = re.sub(r'\d+', '*', text)
print(new_text) # 输出: 今天是****年*月**日
# 分割字符串
text = "Hello,World!Python"
parts = re.split(r'[!,]', text)
print(parts) # 输出: ['Hello', 'World', 'Python']
5. Unicode处理
# Unicode编码和解码
s = "你好"
bytes_data = s.encode('utf-8') # 编码为UTF-8字节
print(bytes_data) # 输出: b'\xe4\xbd\xa0\xe5\xa5\xbd'
decoded_s = bytes_data.decode('utf-8') # 解码为字符串
print(decoded_s) # 输出: 你好
以上是Python中字符串处理的一些常用操作和方法。掌握这些技巧可以帮助你更高效地处理和操作字符串数据。