【问题标题】:similar function for strcmpi in python [duplicate]python中strcmpi的类似功能[重复]
【发布时间】:2012-07-02 05:30:01
【问题描述】:

可能重复:
How do I do a case insensitive string comparison in Python?

我想知道有没有类似strcmpi的功能或者提供一些类似的功能。

假设如果用户输入单词harry potter,并且我的文件中有这个单词以Harry Potter 的形式写入,那么我该如何比较它,因为它只是因为大小写字母而忽略了这一点。

如果我想将“实例”类型的对象转换为 str 怎么办。我怎样才能做到这一点 ?

【问题讨论】:

    标签: python linux string ubuntu-10.04


    【解决方案1】:

    一种简单的方法是在两个字符串上使用.lower(),然后只比较是否相等:

    >>> "Harry Potter".lower() == "harry potter".lower()
    True
    

    【讨论】:

      【解决方案2】:

      您可以在比较之前将两个字符串都转换为小写:

      a = "Harry Potter"
      b = "harry potter"
      
      print a.lower()==b.lower()
      

      【讨论】:

        【解决方案3】:

        你也可以使用string.find

        string.find(s, sub[, start[, end]])
        

        忽略大小写查找所有字符串:

        str = "Hello! How are you?"
        str.lower().find('hello'.lower())
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-02-02
          • 2011-07-15
          • 2013-04-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-05-21
          相关资源
          最近更新 更多