如何在没有Python中replace()函数的情况下替换字符串中句子中所有实例中的字母(例如ABC)?

2024-10-03 00:19:51 发布

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

这是我到目前为止,但为了取代a,b和c,我想知道我如何能纳入取代所有3个字母在所有出现的句子。我也不允许使用replace()函数。你知道吗

def changeLetters(word):
    for letter in word:
        if letter == "a": #I would like to replace a,b and c
            word.replace(letter,"!") #replace the replace() function
    return word

用户输入示例:

Amy buys carrots and apples

用户输出示例:

!my 3uys 8!rrots !nd !pples

Tags: and函数用户in示例forifdef
2条回答
word = 'Amy buys carrots and apples'
result = ''.join(['!' if x == 'a' else '3' if x == 'b' else '8' if x == 'c' else x for x in word.lower()])
result
'!my 3uys 8!rrots !nd !pples'

回答:

first_word = "Amy buys carrots and apples"
def changeLetters(word):
    word_list = [] #creates a list to be filled by letters
    for letter in word: # fills the list with letters from string
        if letter == "a" or letter == "b" or letter == "c": #searches for a b or c
            letter = "!" #replaces a b or c with !
        word_list.append(letter) # appends the current letter to the list
    new_word = "".join(word_list) #joins the letters in the list into a string
    return new_word # returns the value of the new word
print(changeLetters(first_word))

您可以修改或插入“if”语句以替换大写“A”,或根据需要为字母指定不同的替换字符。你知道吗

相关问题 更多 >