首页 > 解决方案 > 如何向字符串中的空格添加不同的字符?(或用不同的字符或数字替换字符串中的特定单词。)

问题描述

如何将字符/数字添加到空格,如下所示:

Today the ---- is cloudy, but there is no ----.

Today the --a)-- is cloudy, but there is no --b)--.(desired result)

如您所见,空格不会被固定字符替换,这使replace()我使用 python 方法变得复杂。

标签: pythonstringreplacetext-manipulation

解决方案


您可以使用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)

演示


推荐阅读