s = 'Python is amazing and Python is powerful'
# 查找
print(s.find('Python')) # 0
print(s.find('Python', 10)) # 25 (从索引10开始查找)
print(s.rfind('Python')) # 25 (从右侧开始查找)
# index() 方法类似于 find(),但在未找到时会引发 ValueError
try:
print(s.index('Java'))
except ValueError:
print("'Java' not found in the string")
# 计数
print(s.count('Python')) # 2
# 替换
print(s.replace('Python', 'Java')) # 'Java is amazing and Java is powerful'
print(s.replace('Python', 'Java', 1)) # 'Java is amazing and Python is powerful'
name = 'Alice'
age = 30
print('My name is %s and I am %d years old.' % (name, age))
# 'My name is Alice and I am 30 years old.'
# 使用字典
print('%(name)s is %(age)d years old.' % {'name': 'Bob', 'age': 25})
# 'Bob is 25 years old.'
str.format() 方法
print('My name is {} and I am {} years old.'.format(name, age))
# 'My name is Alice and I am 30 years old.'
# 使用索引
print('The {1} {0} {2}'.format('brown', 'quick', 'fox')) # 'The quick brown fox'
# 使用命名参数
print('The {adj} {noun}'.format(adj='happy', noun='programmer')) # 'The happy programmer'
# 格式化选项
pi = 3.14159
print('Pi is approximately {:.2f}'.format(pi)) # 'Pi is approximately 3.14'
f-strings (Python 3.6+)
name = 'Charlie'
age = 35
print(f'My name is {name} and I am {age} years old.')
# 'My name is Charlie and I am 35 years old.'
# 在f-string中使用表达式
print(f'2 + 2 = {2 + 2}') # '2 + 2 = 4'
# 格式化选项
import datetime
now = datetime.datetime.now()
print(f'Current time: {now:%Y-%m-%d %H:%M:%S}') # 例如:'Current time: 2023-04-13 15:30:45'
import re
text = "The quick brown fox jumps over the lazy dog" # 查找所有单词
words = re.findall(r'\w+', text)
print(words) # ['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
# 替换
new_text = re.sub(r'fox', 'cat', text)
print(new_text)
# "The quick brown cat jumps over the lazy dog"
# 分割
parts = re.split(r'\s+', text)
print(parts) # ['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
7.性能考虑
在处理大量字符串时,性能是一个重要因素。以下是一些提高字符串操作性能的技巧:
使用 join() 而不是 + 进行多个字符串的拼接。
对于需要多次修改的字符串,考虑使用 list 存储字符,最后再 join。
使用 str.translate() 进行批量字符替换,比多次调用 replace() 更快。
对于大文本的处理,考虑使用生成器和迭代器来减少内存使用。
# 示例:高效地构建大字符串
def build_string(n):
parts = []
for i in range(n):
parts.append(f"Part {i}")
return ' '.join(parts)
large_string = build_string(10000)