假设有一个多字符的片断重复出现,把"really"、"really really ",以及任意数量连续出现的"really"字符串换成一个简单的"very ” ( Billy tried really hard Sally tried really really hard Timmy tried really really really hard Johnny tried really really really really hard )
时间: 2023-07-13 10:09:51 浏览: 66
某字符串在另一字符串中出现的次数的问题
将这个字符串中的重复出现的"really"字符串替换成一个简单的"very"字符串,可以使用正则表达式来实现。具体的实现方式如下:
```python
import re
text = "Billy tried really hard Sally tried really really hard Timmy tried really really really hard Johnny tried really really really really hard"
pattern = r"\b(really\s+)+"
replacement = "very "
result = re.sub(pattern, replacement, text)
print(result)
```
输出结果为:`Billy tried very hard Sally tried very hard Timmy tried very hard Johnny tried very hard`。
阅读全文