【问题标题】:Check if string contains only whitespace检查字符串是否仅包含空格
【发布时间】:2011-01-25 04:56:37
【问题描述】:

如何测试字符串是否只包含空格?

示例字符串:

  • " "(空格、空格、空格)

  • " \t \n "(空格、制表符、空格、换行符、空格)

  • "\n\n\n\t\n"(换行符、换行符、换行符、制表符、换行符)

【问题讨论】:

  • 换行符是空格吗? Tab 应该是一对多的空格。

标签: python text whitespace


【解决方案1】:

使用str.isspace() 方法:

如果字符串中只有空白字符且至少有一个字符,则返回True,否则返回False

如果在 Unicode 字符数据库(参见 unicodedata)中,一个字符是空白字符,或者它的一般类别是 Zs(“分隔符,空格”),或者它的双向类是 WS、B 或 S 之一。

将其与处理空字符串的特殊情况结​​合起来。

或者,您可以使用str.strip() 并检查结果是否为空。

【讨论】:

  • 如果字符串包含不间断空格、字符代码 U+00A0ALT+160,则在 Python 2.4 中将失败。但是,在 Python 2.7 中看起来已修复。
  • 请记住,这不会检查 None''
  • 在 python 2.7.13 中, isspace() 会将不间断空格视为空格。不错!
  • 您可能还想排除空字符串,在这种情况下您可以这样做:if len(str) == 0 or str.isspace():
  • @Joe len(my_str) == 0 也可以写成not my_str
【解决方案2】:

您可以使用str.isspace() 方法。

【讨论】:

    【解决方案3】:

    str.isspace() 返回 False 以获得有效且空的字符串

    >>> tests = ['foo', ' ', '\r\n\t', '']
    >>> print([s.isspace() for s in tests])
    [False, True, True, False]
    

    因此,检查not 还将评估None 类型和''""(空字符串)

    >>> tests = ['foo', ' ', '\r\n\t', '', None, ""]
    >>> print ([not s or s.isspace() for s in tests])
    [False, True, True, True, True, True]
    

    【讨论】:

    • 为什么选择让它返回True for None
    【解决方案4】:

    你想使用isspace()方法

    str.isspace()

    如果字符串中只有空白字符,则返回 true 并且 至少有一个字符,否则为假。

    这是在每个字符串对象上定义的。这是您特定用例的使用示例:

    if aStr and (not aStr.isspace()):
        print aStr
    

    【讨论】:

    【解决方案5】:

    检查 split() 方法给出的列表的长度。

    if len(your_string.split()==0:
         print("yes")
    

    或者 将 strip() 方法的输出与 null 进行比较。

    if your_string.strip() == '':
         print("yes")
    

    【讨论】:

    • 没有理由拆分字符串,len() 适用于字符串。此外,OP 并没有要求测试空字符串,而是要求测试一个全是空格的字符串。你的第二种方法虽然不错。此外,python 中不需要围绕条件的括号。
    • 奇怪的是,第一种方法实际上比没有个字符是空格的好方法,如果将==0替换为==1
    • if len(your_string.split())==0: --> if not your_string.split():, if your_string.strip() == '': --> if not your_string.strip():.无论如何,第一个不如现有的解决方案,第二个已经在其他答案中提到过。
    【解决方案6】:

    对于那些期望像 apache StringUtils.isBlank 或 Guava Strings.isNullOrEmpty 这样的行为的人:

    if mystring and mystring.strip():
        print "not blank string"
    else:
        print "blank string"
    

    【讨论】:

      【解决方案7】:

      我假设在您的场景中,空字符串是真正为空的字符串或包含所有空格的字符串。

      if(str.strip()):
          print("string is not empty")
      else:
          print("string is empty")
      

      请注意,这不会检查 None

      【讨论】:

      • 现有答案不是已经涵盖了吗?
      【解决方案8】:

      这是一个适用于所有情况的答案:

      def is_empty(s):
          "Check whether a string is empty"
          return not s or not s.strip()
      

      如果变量为 None,它将在 not s 处停止并且不会进一步评估(因为 not None == True)。显然,strip() 方法处理了制表符、换行符等常见情况。

      【讨论】:

      • 因为not None == True 直接说None is False 可能更清楚。此外,== 不应用于这些比较。
      【解决方案9】:

      我用了以下:

      if str and not str.isspace():
        print('not null and not empty nor whitespace')
      else:
        print('null or empty or whitespace')
      

      【讨论】:

      • null 你的意思是None 吗?
      【解决方案10】:

      检查字符串是否只是空格或换行符

      使用这个简单的代码

      mystr = "      \n  \r  \t   "
      if not mystr.strip(): # The String Is Only Spaces!
          print("\n[!] Invalid String !!!")
          exit(1)
      mystr = mystr.strip()
      print("\n[*] Your String Is: "+mystr)
      

      【讨论】:

        【解决方案11】:

        类似于c#字符串静态方法isNullOrWhiteSpace。

        def isNullOrWhiteSpace(str):
          """Indicates whether the specified string is null or empty string.
             Returns: True if the str parameter is null, an empty string ("") or contains 
             whitespace. Returns false otherwise."""
          if (str is None) or (str == "") or (str.isspace()):
            return True
          return False
        
        isNullOrWhiteSpace(None) -> True // None equals null in c#, java, php
        isNullOrWhiteSpace("")   -> True
        isNullOrWhiteSpace(" ")  -> True
        

        【讨论】:

        • 你可以return (str is None) or (str == "") or (str.isspace())
        • 哦,None"" 都是假的,所以你可以:return not str or str.isspace()
        • @AMC 你能详细说明一下吗,我不明白你想说什么。
        猜你喜欢
        • 2011-01-03
        • 2021-08-17
        • 1970-01-01
        • 1970-01-01
        • 2019-11-02
        • 1970-01-01
        • 2010-12-19
        相关资源
        最近更新 更多