【问题标题】:string method doesn't work even if I pass it to a parameter python即使我将字符串方法传递给参数python,它也不起作用
【发布时间】:2021-12-25 23:31:41
【问题描述】:

您好,我是一名 C# 程序员,但我认为学习 python 也很好,所以我正在学习 python 我有这段代码

def disemvowel(string_):
    for n in string_:
        if(n is 'a' or 'e' or 'u' or 'o' or 'i'):
            string_ = string_.replace('n' , '')
    return string_
print(disemvowel('Hello'))

我声明了一个从字符串中删除元音的函数我搜索了它的问题但我找不到任何东西我什至将替换函数的返回值传递给字符串然后传递它我的代码问题是什么? 谢谢你的回答

【问题讨论】:

    标签: python string replace


    【解决方案1】:

    is 用于比较 ID。在您的情况下,n 和“a”没有必要具有相同的内存位置。您可以将其更改为== 以比较值。如果 n 的值为“a”,则 n=="a" 应返回 True。当两者的位置相同时,is 将返回 True。即使值正确,它也会返回False。或者您也可以使用in。如果变量存在于字符串或可迭代数据类型中,in 将返回 True。你的代码是:

    1. 使用==:
    def disemvowel(string_):
        for n in string_:
            if n.lower()=="a" or n.lower()=="e" or n.lower()=="i" or n.lower()=="o" or n.lower()=="u":
                string_ = string_.replace(n,'')
        return string_
    print(disemvowel('Hello'))
    
    1. 使用in
    def disemvowel(string_):
        for n in string_:
            if n.lower() in ["a","e","i","o","u"]:
                string_ = string_.replace(n,'')
        return string_
    print(disemvowel('Hello'))
    

    【讨论】:

      【解决方案2】:

      试试这个:

      def disemvowel(string_):
          res = ''
          for n in string_:
              if n not in ['a' , 'e',  'u' ,'o' , 'i']:
                  res += n
          return res
      print(disemvowel('Hello'))
      

      【讨论】:

        【解决方案3】:
        def disemvowel(string_):
            for n in string_:
                if n in 'aeiouAEIOU':
                    string_ = string_.replace(n, '')
            return string_
        
        print(disemvowel('Hello')) 
        
        
        Output: 'Hll'
        

        如果你写if n in 'aeiouAEIOU',你不必使用所有的或运算符。

        【讨论】:

        • 非常感谢,但为什么我的代码不起作用?
        • 这是因为你的 if 语句。你的版本应该是这样的 --> 如果 n == 'a' or n == 'e' or n == 'i' or n == 'o' or n == 'u': ...跨度>
        猜你喜欢
        • 1970-01-01
        • 2020-09-16
        • 1970-01-01
        • 2015-02-04
        • 1970-01-01
        • 1970-01-01
        • 2014-03-03
        • 1970-01-01
        • 2016-09-15
        相关资源
        最近更新 更多