Python替换字符串给出一个单词

时间:2017-02-07 07:56:32

标签: 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 abcabcabcabc abcabc'而不是'ab cabc ab'

2 个答案:

答案 0 :(得分:1)

更改如下:

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'

答案 1 :(得分:0)

如果你不能使用itertools 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)
相关问题