Python替换给定单词的字符串

2024-03-29 07:25:55 发布

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

嗨,有人知道如何制作一个函数,用给定单词中的字符(无限重复)替换字符串中的每个字母字符。如果一个字符不是字母顺序,它应该留在原来的位置。此外,这必须在不导入任何内容的情况下完成。你知道吗

def replace_string(string,word)
'''
>>>replace_string('my name is','abc')
'ab cabc ab'

到目前为止,我想到了:

def replace_string(string,word):
    new=''
    for i in string:
        if i.isalpha():
            new=new+word
        else: new=new+i
    print(new)

但是,此函数只打印“abcabc abcabc abcabc”而不是“ab cabc ab”


Tags: 函数字符串内容newstringab顺序def
2条回答

变更如下:

def replace(string, word):
    new, pos = '', 0
    for c in string:
        if c.isalpha():
            new += word[pos%len(word)]  # rotate through replacement string
            pos += 1  # increment position in current word
        else: 
            new += c
            pos = 0  # reset position in current word
    return new

>>> replace('my name is greg', 'hi')
'hi hihi hi hihi'

如果不能使用^{} module,请首先创建一个生成器函数,该函数将无限期地遍历替换字:

def cycle(string):
    while True:
        for c in string:
            yield c

然后,稍微调整一下现有功能:

def replace_string(string,word):
    new=''
    repl = cycle(word)
    for i in string:
        if i.isalpha():
            new = new + next(repl)
        else: 
            new = new+i
    return new

输出:

>>> replace_string("Hello, I'm Greg, are you ok?", "hi")
"hihih, i'h ihih, ihi hih ih?"

另一种编写方法(但我认为第一个版本更具可读性,因此更好):

def replace_string(string,word):
    return ''.join(next(cycle(word)) if c.isalpha() else c for c in string)

相关问题 更多 >