欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

thinking in c and python

程序员文章站 2024-02-29 17:31:16
...
def censor(text, word):
    text_backup = ""
    text_i = 0
    word_len = len(word)
    text_len = len(text)
    while(True):
        text_to = text_i + word_len
        if text_i < text_len:
            if text_to <= text_len:
                if text[text_i:text_to] == word:
                    text_i += word_len
                    for i in range(0, word_len):
                        text_backup += "*"
                else:
                    text_backup += text[text_i]
                    text_i += 1
            else:
                text_backup += text[text_i]
                text_i += 1
        else:
            break
    return text_backup

print censor("hey hey hey","hey")            

 and the other (from Petr Chmelař)

def censor(text, word):
    index = 0
    while index >= 0:
        index = text.find(word)
        if index >= 0:
            for i in range(index,index+len(word)):
                text = text[:i] + '*' + text[i+1:]
    return text

print censor("hey hey hey","hey")            

 

转载于:https://www.cnblogs.com/Jason-Ch/archive/2013/04/02/2994924.html