如何向字符串中的空格添加不同的字符?(或用不同的字符或数字替换字符串中的特定单词。)

how can I add different character to blank spaces in a string?(or replace specific word in a string with different characters or numbers.)

如何将 characters/numbers 添加到这样的空白处:

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

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

如您所见,空格没有被固定字符替换,这使得使用 python replace() 方法对我来说很复杂。

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

DEMO