簡體   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