替换字符串,而不是不使用的字符。替换并连接字符串和字符

2024-05-14 16:16:12 发布

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

有人问了一个类似的问题,但这里的所有帖子都是指替换单个字符。我想用一个字符串替换整个单词。我已经把它换了,但是我不能打印中间有空格的

下面是替换它的函数replace

def replace(a, b, c):
    new = b.split()
    result = ''
    for x in new:
        if x == a:
            x = c
        result +=x
    print(' '.join(result))

称之为:

replace('dogs', 'I like dogs', 'kelvin')

我的结果是:

i l i k e k e l v i n 

我要找的是:

I like kelvin

Tags: 函数字符串newfordefresult字符单词
3条回答

子串和空间保持方法:

def replace(a, b, c):
    # Find all indices where 'a' exists
    xs = []
    x = b.find(a)
    while x != -1:
        xs.append(x)
        x = b.find(a, x+len(a))

    # Use slice assignment (starting from the last index)
    result = list(b)
    for i in reversed(xs):
        result[i:i+len(a)] = c

    return ''.join(result)

>>> replace('dogs', 'I like dogs dogsdogs and   hotdogs', 'kelvin')
'I like kelvin kelvinkelvin and   hotkelvin'

只要把result列成一个列表,加入就可以了:

result = []

您只需生成一个长字符串并加入其字符

这里的问题是result是一个字符串,当调用join时,它将接受result中的每个字符并将其连接到一个空格中

相反,使用listappend来对其进行压缩(这也比在字符串上使用+=更快),并通过解包将其打印出来

即:

def replace(a, b, c):
    new = b.split(' ')
    result = []
    for x in new:
        if x == a:
            x = c
        result.append(x)
    print(*result)

print(*result)将提供result列表的元素作为位置参数进行打印,打印时使用默认的空格分隔

"I like dogs".replace("dogs", "kelvin")当然可以在这里使用,但我很确定这不符合要点

相关问题 更多 >

    热门问题