Tutorial Study Image

Python isspace()

Python 中的 isspace() 函数用于检查字符串中的所有字符是否都是空白字符。如果字符串全部由空白字符(制表符、空格、换行符等)组成,则该函数返回 True,否则返回 False。


string.isspace() 
 

isspace() 参数

isspace() 方法不接受任何参数。

isspace() 返回值

返回值始终为布尔值。如果字符串为空,则该函数返回 False。

输入 返回值
所有空白字符 True
至少一个非空白字符 False

Python 中 isspace() 方法的示例

示例 1:isspace() 在 Python 中如何工作?


string = '   \t'
print(string.isspace())

string = ' a '
print(string.isspace())

string = ''
print(string.isspace())
 

输出


True
False
False

示例 2:如何在 Python 中使用 isspace()?


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