繁体   English   中英

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

[英]How to replace letters (ex. ABC) in all instances in a sentence in a string without the replace() function in Python?

这是我到目前为止所拥有的,但为了替换 a、b 和 c,我想知道如何将替换句子中所有出现的所有 3 个字母。 我也不允许使用 replace() function。

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

用户 output 示例:

!my 3uys 8!rrots !nd !pples
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”或根据需要为字母分配不同的替换字符。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM