python - 如何向字符串中的空格添加不同的字符?(或用不同的字符或数字替换字符串中的特定单词。)
问题描述
如何将字符/数字添加到空格,如下所示:
Today the ---- is cloudy, but there is no ----.
Today the --a)-- is cloudy, but there is no --b)--.(desired result)
如您所见,空格不会被固定字符替换,这使replace()
我使用 python 方法变得复杂。
解决方案
您可以使用re.sub()
. 它允许您使用函数作为替换,因此该函数可以在每次调用时递增字符。我已经将该函数编写为生成器。
import re
def next_char():
char = 'a'
while True:
yield char
char = chr(ord(char) + 1)
if char > 'z':
char = 'a'
seq = next_char()
str = 'Today the ---- is cloudy, but there is no ----.'
str = re.sub(r'----', lambda x: ('--' + next(seq) + ')--'), str)
print(str)
推荐阅读
- javascript - axios 在我的字符串中间添加 52
- excel - 复制具有匹配工作表名称的数据
- python - 仅当有任何新可用时才下载 sonarqube 包的 Python 脚本
- spring - 为两个不同的入口点创建 bean
- gitlab - 检索 Jenkins 文件和 Git 存储库
- sql-server - 如何在 ASP.NET Core 中使用 Serilog 禁用自动日志记录
- javascript - 检查文本输入字段是否为空或包含数字
- python - 如何重新排列数据在多列之间拆分的熊猫表
- r - 如何在谷歌 colab R 上使用 gpu?
- reactjs - 反应:备忘录不起作用 - OnClick 按钮导致重新渲染