Python 中的 isspace() 函数用于检查字符串中的所有字符是否都是空白字符。如果字符串全部由空白字符(制表符、空格、换行符等)组成,则该函数返回 True,否则返回 False。
string.isspace()
isspace() 方法不接受任何参数。
返回值始终为布尔值。如果字符串为空,则该函数返回 False。
| 输入 | 返回值 |
|---|---|
| 所有空白字符 | True |
| 至少一个非空白字符 | False |
string = ' \t'
print(string.isspace())
string = ' a '
print(string.isspace())
string = ''
print(string.isspace())
输出
True False False
string = '\t \n'
if string.isspace() == True:
print('String full of whitespace characters')
else:
print('String contains non-whitespace characters')
string = '15+3 = 18'
if string.isspace() == True:
print('String full of whitespace characters')
else:
print('String contains non-whitespace characters.')
输出
String full of whitespace characters String contains non-whitespace characters