如何在Python中检查文本是否为“空”(空格,制表符,换行符)?
可以通过仅检查空白字符的出现来检查字符串。我们可以使用2种方法检查字符串是否仅包含空格字符。首先是使用方法isspace()。
示例
print('Hello world'.isspace())
print(' '.isspace())输出结果
False True
您也可以将正则表达式用于相同的结果。为了只匹配空格,我们可以使用正则表达式元字符\s调用re.match(regex,string),如下所示:“^\s*$”。
示例
import re
print(bool(re.match('^\s+$', ' abc')))
print(bool(re.match('^\s+$', ' ')))输出结果
False True