【问题标题】:Replace method issue替换方法问题
【发布时间】:2017-01-05 23:43:40
【问题描述】:

我的这段代码似乎工作得很好,只是它省略了一个“e”!该代码旨在循环遍历给定的字符串,删除元音,然后返回新的反元音字符串。

def anti_vowel(text):
    anti_v = ''
    for c in text:
        if c in "aeiouAEIOU":
            anti_v = text.replace(c, '')
        else:
            anti_v.join(c)
    return anti_v

测试代码:

anti_vowel("Hey look Words!")

这会返回“Hey lk Wrds!”

什么给了?谢谢!

【问题讨论】:

  • anti_v.join(c) 不会像您想象的那样做任何事情。 text.replace(c, '') 也不会替换 'e''o' 或其他的特定实例;它替换所有实例。每次执行另一个替换时,您也会丢弃旧的替换。

标签: python string for-loop replace


【解决方案1】:

您可以使用推导来连接字符串中不是元音的所有字符:

def anti_vowel(text):
    return ''.join(c for c in text if c not in 'aeiouAEIOU')

【讨论】:

    【解决方案2】:

    我认为问题在于您将值存储在 anti_v 但每次运行循环时,您都将 anti_v 的值替换为 text.replace(c, '') 的值,但是 text 变量不改变。 例如,如果文本是“aae”。

    c = 'a' ---> anti_v = 'aae'.replace('a', '') --> anti_v='e'
    c = 'a' ---> anti_v = 'aae'.replace('a', '') --> anti_v='e'
    c = 'e' ---> anti_v = 'aae'.replace('e', '') --> anti_v='aa'
    

    所以在这种情况下,anti_vowel 的返回值将是 'aa' 而不是空字符串。

    解决此问题的一种方法是按照@VHarisop 的建议进行操作。

    您还可以查看this 线程以查看删除字符串上元音的其他选项。

    【讨论】:

      【解决方案3】:

      每次运行循环时,都会对 text 参数进行替换。 但是当您进行替换时,原始值不会改变。因此,下次您替换时,您将在原始字符串上执行此操作。例如:

      print(text.replace('e', '')) # Hy hy look txt!
      print(text) # Hey hey look text!
      

      它似乎适用于其他元音,因为您的 else 将 c 连接到 anti_v。

      不过,您根本不需要 else。只需将 anti_v 设置为 text 并在 anti_v 上进行替换。这将解决您的问题。

      def anti_vowel(text):
          anti_v = text
          for c in text:
              if c in "aeiouAEIOU":
                  anti_v = anti_v.replace(c, '')
      
          return anti_v
      

      或者只是一起删除 anti_v 变量并使用文本:

      def anti_vowel(text):
          for c in text:
              if c in "aeiouAEIOU":
                  text = text.replace(c, '')
      
          return text
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-08-28
        • 2017-02-27
        • 1970-01-01
        • 2011-01-22
        • 1970-01-01
        • 2014-11-24
        • 2013-12-06
        相关资源
        最近更新 更多