【问题标题】:Checking whether a string starts with XXXX检查字符串是否以 XXXX 开头
【发布时间】:2012-02-06 20:09:54
【问题描述】:

我想知道如何在 Python 中检查字符串是否以“hello”开头。

在 Bash 中我通常这样做:

if [[ "$string" =~ ^hello ]]; then
 do something here
fi

如何在 Python 中实现相同的功能?

【问题讨论】:

    标签: python string string-comparison


    【解决方案1】:
    aString = "hello world"
    aString.startswith("hello")
    

    关于startswith的更多信息。

    【讨论】:

      【解决方案2】:

      RanRag has already answered 用于您的具体问题。

      但是,更一般地说,您正在做什么

      if [[ "$string" =~ ^hello ]]
      

      是一个 regex 匹配。要在 Python 中做同样的事情,你可以这样做:

      import re
      if re.match(r'^hello', somestring):
          # do stuff
      

      显然,在这种情况下,somestring.startswith('hello') 更好。

      【讨论】:

      • 只是想补充一点,对于我正在做的事情,re.match 和 re.sub 总是比任何其他方法慢得多。
      【解决方案3】:

      也可以这样..

      regex=re.compile('^hello')
      
      ## THIS WAY YOU CAN CHECK FOR MULTIPLE STRINGS
      ## LIKE
      ## regex=re.compile('^hello|^john|^world')
      
      if re.match(regex, somestring):
          print("Yes")
      

      【讨论】:

        【解决方案4】:

        如果您想将 多个 个单词匹配到您的魔法单词,您可以将要匹配的单词作为元组传递:

        >>> magicWord = 'zzzTest'
        >>> magicWord.startswith(('zzz', 'yyy', 'rrr'))
        True
        

        startswith 接受一个字符串或字符串元组。

        【讨论】:

          【解决方案5】:

          我做了一个小实验,看看这些方法中的哪一种

          • string.startswith('hello')
          • string.rfind('hello') == 0
          • string.rpartition('hello')[0] == ''
          • string.rindex('hello') == 0

          返回某个字符串是否以另一个字符串开头最有效。

          这是我进行的众多测试运行之一的结果,其中每个列表都按顺序显示(以秒为单位) 解析每个列表中的 500 万个在我使用的while 循环的每次迭代中,上述表达式:

          ['startswith: 1.37', 'rpartition: 1.38', 'rfind: 1.62', 'rindex: 1.62']
          ['startswith: 1.28', 'rpartition: 1.44', 'rindex: 1.67', 'rfind: 1.68']
          ['startswith: 1.29', 'rpartition: 1.42', 'rindex: 1.63', 'rfind: 1.64']
          ['startswith: 1.28', 'rpartition: 1.43', 'rindex: 1.61', 'rfind: 1.62']
          ['rpartition: 1.48', 'startswith: 1.48', 'rfind: 1.62', 'rindex: 1.67']
          ['startswith: 1.34', 'rpartition: 1.43', 'rfind: 1.64', 'rindex: 1.64']
          ['startswith: 1.36', 'rpartition: 1.44', 'rindex: 1.61', 'rfind: 1.63']
          ['startswith: 1.29', 'rpartition: 1.37', 'rindex: 1.64', 'rfind: 1.67']
          ['startswith: 1.34', 'rpartition: 1.44', 'rfind: 1.66', 'rindex: 1.68']
          ['startswith: 1.44', 'rpartition: 1.41', 'rindex: 1.61', 'rfind: 2.24']
          ['startswith: 1.34', 'rpartition: 1.45', 'rindex: 1.62', 'rfind: 1.67']
          ['startswith: 1.34', 'rpartition: 1.38', 'rindex: 1.67', 'rfind: 1.74']
          ['rpartition: 1.37', 'startswith: 1.38', 'rfind: 1.61', 'rindex: 1.64']
          ['startswith: 1.32', 'rpartition: 1.39', 'rfind: 1.64', 'rindex: 1.61']
          ['rpartition: 1.35', 'startswith: 1.36', 'rfind: 1.63', 'rindex: 1.67']
          ['startswith: 1.29', 'rpartition: 1.36', 'rfind: 1.65', 'rindex: 1.84']
          ['startswith: 1.41', 'rpartition: 1.44', 'rfind: 1.63', 'rindex: 1.71']
          ['startswith: 1.34', 'rpartition: 1.46', 'rindex: 1.66', 'rfind: 1.74']
          ['startswith: 1.32', 'rpartition: 1.46', 'rfind: 1.64', 'rindex: 1.74']
          ['startswith: 1.38', 'rpartition: 1.48', 'rfind: 1.68', 'rindex: 1.68']
          ['startswith: 1.35', 'rpartition: 1.42', 'rfind: 1.63', 'rindex: 1.68']
          ['startswith: 1.32', 'rpartition: 1.46', 'rfind: 1.65', 'rindex: 1.75']
          ['startswith: 1.37', 'rpartition: 1.46', 'rfind: 1.74', 'rindex: 1.75']
          ['startswith: 1.31', 'rpartition: 1.48', 'rfind: 1.67', 'rindex: 1.74']
          ['startswith: 1.44', 'rpartition: 1.46', 'rindex: 1.69', 'rfind: 1.74']
          ['startswith: 1.44', 'rpartition: 1.42', 'rfind: 1.65', 'rindex: 1.65']
          ['startswith: 1.36', 'rpartition: 1.44', 'rfind: 1.64', 'rindex: 1.74']
          ['startswith: 1.34', 'rpartition: 1.46', 'rfind: 1.61', 'rindex: 1.74']
          ['startswith: 1.35', 'rpartition: 1.56', 'rfind: 1.68', 'rindex: 1.69']
          ['startswith: 1.32', 'rpartition: 1.48', 'rindex: 1.64', 'rfind: 1.65']
          ['startswith: 1.28', 'rpartition: 1.43', 'rfind: 1.59', 'rindex: 1.66']
          

          我相信从一开始就很明显startswith 方法会最有效,因为返回一个字符串是否以指定字符串开头是它的主要目的。

          让我吃惊的是,看似不切实际的string.rpartition('hello')[0] == '' 方法总是会在string.startswith('hello') 方法之前,时不时地找到一种列在第一位的方法。结果表明,使用str.partition 来确定一个字符串是否以另一个字符串开头比同时使用rfindrindex 更有效。

          我注意到的另一件事是string.rfind('hello') == 0string.rindex('hello') == 0 进行了一场精彩的战斗,各自从第四名上升到第三名,从第三名下降到第四名,这是有道理的,因为它们的主要目的是一样的。

          代码如下:

          from time import perf_counter
          
          string = 'hello world'
          places = dict()
          
          while True:
              start = perf_counter()
              for _ in range(5000000):
                  string.startswith('hello')
              end = perf_counter()
              places['startswith'] = round(end - start, 2)
          
              start = perf_counter()
              for _ in range(5000000):
                  string.rfind('hello') == 0
              end = perf_counter()
              places['rfind'] = round(end - start, 2)
          
              start = perf_counter()
              for _ in range(5000000):
                  string.rpartition('hello')[0] == ''
              end = perf_counter()
              places['rpartition'] = round(end - start, 2)
          
              start = perf_counter()
              for _ in range(5000000):
                  string.rindex('hello') == 0
              end = perf_counter()
              places['rindex'] = round(end - start, 2)
              
              print([f'{b}: {str(a).ljust(4, "4")}' for a, b in sorted(i[::-1] for i in places.items())])
          

          【讨论】:

            猜你喜欢
            • 2023-01-01
            • 2011-05-04
            • 1970-01-01
            • 1970-01-01
            • 2019-08-24
            • 2015-04-15
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多