【问题标题】:Remove certain word from string从字符串中删除某些单词
【发布时间】:2022-01-24 03:56:42
【问题描述】:

程序需要从单词中删除元音。 我尝试了一些方法,但不知道为什么它不起作用。

代码:

n = input("Type word: ")
words = []
words.append(n)

while n != "":
    n = input("Type word: ")
    if n != "":
        words.append(n)
test = str(words)
print(test)
vowels = ("A", "B", "C", "D")
for i in test:
    if i in vowels:
        test.replace("A", "")
print(test)

【问题讨论】:

  • B、C 和 D 不是元音
  • 另外,要找出为什么您的程序不工作,您应该先找出什么出了问题。
  • 这里只是为了测试,对于用户输入 ABCDabcd 输出是一样的。

标签: python string


【解决方案1】:

replace方法返回修改后字符串的副本,它不会改变原始字符串,你需要这样做:

test = test.replace("A", "")

【讨论】:

    【解决方案2】:

    您可以做的只是遍历输入中提供的每个字母,并检查它是否在元音列表中;如果不是,则将其添加到一个单独的字符串中,该字符串将包含您已清理的消息,不包含任何元音。

    VOWELS = ["a", "e", "i", "o", "u"] # Define a list of vowels.
    message = input("Type word: ") # Get the input.
    strippedMessage = "" # The separate variable to hold our parsed input.
    
    for letter in message: # For every letter within the input.
        if letter.lower() not in VOWELS: # If the letter is not a vowel.
            strippedMessage += letter # Add it to the stripped message.
    print(strippedMessage)
    
    Input: this is a sample message
    Output: ths s  smpl mssg
    

    【讨论】:

    • 这适用于 tnx,但在我追逐用户在新行中输入单词时,输入结尾是空输入。输出是一个在另一个之下。
    【解决方案3】:

    使用正则表达式从字符串中删除所有元音:

    import re
    str = input("Type word: ")
    print(re.sub("[aeiou]", "", str, flags=re.IGNORECASE))
    

    【讨论】:

      【解决方案4】:

      要替换元音,您可以使用这样的嵌套循环:

      for i in test:
         for j in vowels:
            if j in i.upper():
                test = test.replace(i, "")
      print(test)
      

      【讨论】:

      • 如果用户没有输入任何内容,输入过程就会结束。
      • 哦,我明白了。然后保留while循环,用这段代码替换for循环,看看是否适合你。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-21
      相关资源
      最近更新 更多