Skip to main content
 首页 » 编程设计

python之用单词替换字母

2025年05月04日13jiqing9006

我想知道如何在不使用任何内置函数的情况下编写一个用单词替换字母的函数。例如,eyeForI(“William”) 返回 “Weyelleyeam”,它将每个 i 替换为 eye。

我知道如何使用一个内置函数来做到这一点,我已经在这里写了类似的东西(尽管在这种情况下它用不同的词改变了一个词):

def stringChange(s): 
    for old, new in ( 
        ("can't", "can not"), 
        ("shouldn't", "should not"), 
        ("don't", "do not"), 
        ("won't", "will not"), 
        ): 
        s = s.replace(old, new) 
    if "!" in s: 
        s=s.upper() 
 
    return s 

但我不知道如何在不使用任何内置函数的情况下编写它。

我知道我必须使用 for 循环。

请您参考如下方法:

字符串是不可变的,因此您需要将其转换为列表,进行更改,然后再转换回字符串。对于您的示例,

def eyeForI(word): 
    word = list(word) 
    j = 0 
    while j < len(word): 
        if word[j] == 'i': 
            word[j] = 'eye' 
        j += 1 
    word = ''.join(word) 
    return word 

如果您只是学习控制结构,值得一提的是,这也可以通过 for 循环而不是 while 循环来完成。

def eyeForI(word): 
    # convert the string word into a list 
    # word = ['W', 'i', 'l', 'l', 'i', 'a', 'm'] 
    word = list(word) 
    # loop over indices of the list.  len(word) = 7 so i runs from 0-6 
    for j in xrange(len(word)): 
        if word[j] == 'i':      # if the j'th item in word == "i" 
            word[j] = 'eye'     # change it to "eye" 
    word = ''.join(word)        # join method, explained below 
    return word 

join 方法一开始可能会令人困惑。它将使用调用它的字符串作为分隔符(在本例中为 '')来连接其参数(在本例中为 word)的所有元素。所以我们只是说,“使用空字符串连接单词的元素以分隔它们”。请注意,您还可以使用 + 运算符从头开始构建另一个字符串,并根据需要遍历原始 word 字符串(请参阅其他答案)。