如何在Python中检查文本是否为“空”(空格、制表符、换行符)?

2024-04-23 23:18:45 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python中,如何测试字符串是否为空?

例如

"<space><space><space>"为空,也为空

"<space><tab><space><newline><space>",也是

"<newline><newline><newline><tab><newline>"


Tags: 字符串newlinespacetab
3条回答

您想使用^{}方法

str.isspace()

Return true if there are only whitespace characters in the string and there is at least one character, false otherwise.

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

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

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

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

或者,你可以使用

strippedString = yourString.strip()

然后检查strippedString是否为空。

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

相关问题 更多 >