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

2024-09-29 18:55:19 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在空格中添加字符/数字,如下所示:

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

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

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


Tags: the方法notodayis数字result字符
1条回答
网友
1楼 · 发布于 2024-09-29 18:55:19

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

相关问题 更多 >

    热门问题