2024-04-23 23:18:45 发布
网友
在Python中,如何测试字符串是否为空?
例如
"<space><space><space>"为空,也为空
"<space><space><space>"
"<space><tab><space><newline><space>",也是
"<space><tab><space><newline><space>"
"<newline><newline><newline><tab><newline>"等
"<newline><newline><newline><tab><newline>"
您想使用^{}方法
str.isspace()Return true if there are only whitespace characters in the string and there is at least one character, false otherwise.
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] >>>
您想使用^{} 方法
在每个字符串对象上定义的。下面是您的特定用例的使用示例:
如果字符串中只有空白字符且至少有一个字符,则返回true,否则返回false
将其与处理空字符串的特殊情况结合起来。
或者,你可以使用
然后检查strippedString是否为空。
相关问题 更多 >
编程相关推荐