python string isspace() 方法用于检查字符串是否由空格字符组成。 如果输入字符串中的所有字符都是空白字符,并且至少有一个字符,则此方法返回 true。否则,它将返回 false。
如果在 Unicode 字符数据库中,字符的一般类别是 Zs(“分隔符,空格”),或者其双向类是 WS、B 或 S 之一,则该字符为空格。
让我们在下一节中了解此方法的更多详细信息。
语法
以下是 python 字符串 isspace() 方法的语法 -
str.isspace()
参数
python 字符串 isspace() 方法不包含任何参数。
返回值
如果字符串中的所有字符都是空白字符,并且 至少是一个字符,否则为 false。
例普通的空白处 “ ” 是空白字符。
以下是 python 字符串 isspace() 方法的示例。
str = " "
result=str.isspace()
print("Are all the characters of the string spaces?", result)
在执行上述程序时,将生成以下输出 -
Are all the characters of the string spaces? True
例
字母不属于空格字符。在以下示例中,我们将使用字母字符创建字符串 “s” 并使用此方法进行测试。
str = "s"
result=str.isspace()
print("Are all the characters of the string spaces?", result)
以下是执行上述程序得到的输出 -
Are all the characters of the string spaces? False
例
水平制表符间距 '\t' 是空白字符。让我们通过一个例子来测试一下。
str = "\t\t\t"
result=str.isspace()
print("Are all the characters of the string spaces?", result)
通过执行上述程序获得以下输出 -
Are all the characters of the string spaces? True
例
换行符 '\n' 也被视为空白字符。在下面的示例中,我们将创建一个包含换行符的字符串,并验证它是否为空格。
str = "\n"
result=str.isspace()
print("Are all the characters of the string spaces?", result)
上述程序在执行时显示以下输出 -
Are all the characters of the string spaces? True
例
垂直制表符 ('\v')、换页符 ('\f') 和回车符 ('\r') 被视为空白字符。
str = "\v\f\r"
result=str.isspace()
print("Are all the characters of the string spaces?", result)
上述程序的输出显示如下 -
Are all the characters of the string spaces? True