【问题标题】:How to check if a string contains anything else than whitespace如何检查字符串是否包含除空格以外的任何内容
【发布时间】:2019-10-29 13:55:02
【问题描述】:

如何检查python中的字符串中是否有文本或只有空格?

例子:

" " 应该返回 False

"test" 应该返回 True

"tes t " 应该返回 True

【问题讨论】:

  • 你试过什么?您具体需要哪些帮助?

标签: python python-3.x string


【解决方案1】:
teststring = "   "
print(teststring.isspace())

# True

【讨论】:

    【解决方案2】:

    str.strip() 函数将从您的字符串中删除任何前导或尾随空格。

    然后你可以通过检查新字符串的长度轻松检查你想要的内容。

    >>> my_str_with_space = ' \r\n   string   \r\n   '
    >>> my_str_with_space
    ' \r\n   string   \r\n   '
    >>> my_str = my_str_with_space.strip()
    >>> my_str
    'string'
    

    所以创建一个简单的函数来通过检查字符串长度来检查字符串是否为空。

    >>> def str_not_empty(s):
    ...     return bool(len(s))
    

    然后使用它。

    >>> str_not_empty(my_str)
    True
    >>> str_empty = ''
    >>> str_not_empty(str_empty)
    False
    

    (该函数是可选的,但对示例很有用)

    【讨论】:

      猜你喜欢
      • 2016-01-26
      • 1970-01-01
      • 1970-01-01
      • 2012-06-02
      • 1970-01-01
      • 1970-01-01
      • 2013-07-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多