【问题标题】:How to check multiple consecutive spaces in a string with python? [duplicate]如何用python检查字符串中的多个连续空格? [复制]
【发布时间】:2020-08-31 07:08:29
【问题描述】:

我想使用 python 在字符串中查找多个空格。如何检查字符串中是否存在多个空格?

mystring = 'this   is a test'

我尝试了下面的代码,但它不起作用。

if bool(re.search(' +', ' ', mystring))==True:
    # ....

结果必须返回True

【问题讨论】:

标签: python string


【解决方案1】:

你可以使用split(),如果你没有给出分隔符,它会认为空格作为分隔符。拆分后检查长度。如果长度大于一,则有空格。

mystring = 'this   is a test'

if len(mystring.split()) > 1:
    #do something

【讨论】:

    【解决方案2】:

    您可以使用 string.count() 方法: 如果你想检查是否存在多个(多个,无论它们的长度)空格,代码是:

    mystring.count(' ')>1
    
    

    如果要检查是否至少有一个连续的空格,代码是:

    mystring.count('  ')>=1
    

    【讨论】:

    • 如果这是你想要的,请使用in
    【解决方案3】:

    您可以使用 re 并像这样比较字符串:

    import re
    
    mystring = 'this  is a test'
    new_str = re.sub(' +', ' ', mystring)
    
    
    if mystring == new_str:
        print('There are no multiple spaces')
    else:
        print('There are multiple spaces')
    

    【讨论】:

      【解决方案4】:

      您用于re.search 的语法是错误的。应该是re.search(pattern, string, flags=0)

      所以,你可以这样做,搜索 2 个或更多空格:

      import re
      
      def contains_multiple_spaces(s):
          return bool(re.search(r' {2,}', s))
      
      contains_multiple_spaces('no multiple spaces')
      # False
      
      contains_multiple_spaces('here   are multiple spaces')
      # True
      

      【讨论】:

        猜你喜欢
        • 2018-03-03
        • 2015-03-27
        • 2015-06-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-14
        • 2014-06-23
        • 1970-01-01
        相关资源
        最近更新 更多