new_text = re.sub(r'\b\w+\b', capitalize, text) print(new_text) # 输出: This Is A Test Sentence.
3. 使用捕获组进行替换
1 2 3 4 5
import re
text = "Contact me at 123-456-7890 or 987-654-3210." formatted_text = re.sub(r'(\d{3})-(\d{3})-(\d{4})', r'(\1) \2-\3', text) print(formatted_text) # 输出: Contact me at (123) 456-7890 or (987) 654-3210.
4. 结合 flags 使用
1 2 3 4 5
import re
text = "Baked Beans And Spam" new_text = re.sub(r'\sAND\s', ' & ', text, flags = re.IGNORECASE) print(new_text)