【问题标题】:How to replace letters (ex. ABC) in all instances in a sentence in a string without the replace() function in Python?如何在没有Python中的replace()函数的情况下替换字符串中句子中所有实例中的字母(例如ABC)?
【发布时间】:2019-11-16 01:11:39
【问题描述】:

这是我到目前为止所拥有的,但为了替换 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

【问题讨论】:

  • 不清楚您要做什么。您说您要替换 abc,但您的代码(未成功)尝试替换每个字母 but a。你能给出一个示例输出来配合示例输入吗?
  • 您可以通过覆盖它来“替换”该字母。请记住,您可以索引字符串,即如果a = "cat"a[0] 将是ca[1] 将是a 等等。您可以通过执行a[1] = "*" 来使用它,这将使c*t
  • 请发布您想要的结果。
  • @AriCooper-Davis 是的,但是如果这个词是来自用户的输入呢?
  • 如果输入分配给执行函数的变量,我下面的解决方案将在这种情况下工作。

标签: python python-3.x for-loop


【解决方案1】:
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'

【讨论】:

  • 谢谢!但是,如果想用 3 替换 b 并用 8 替换 c 而不是 !替换所有 a、b 和 c
  • ''.join(['3' if x == 'b' else '8' if x == 'c' else x for x in word])
【解决方案2】:

答案:

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”或根据需要为字母分配不同的替换字符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-27
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 2014-03-14
    • 2015-02-12
    • 1970-01-01
    相关资源
    最近更新 更多