當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python String isspace()用法及代碼示例

如果字符串中隻有空白字符,isspace() 方法將返回 True。如果不是,則返回 False。

用於間距的字符稱為空白字符。例如:製表符、空格、換行符等。

用法:

string.isspace()

參數:

isspace() 方法不帶任何參數。

返回:

isspace() 方法返回:

  • True 如果字符串中的所有字符都是空白字符
  • False 如果字符串為空或包含至少一個不可打印字符

示例 1:isspace() 的工作

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

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

s = ''
print(s.isspace())

輸出

True
False
False

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

s = '\t  \n'
if s.isspace() == True:
  print('All whitespace characters')
else:
  print('Contains non-whitespace characters')
  
s = '2+2 = 4'

if s.isspace() == True:
  print('All whitespace characters')
else:
  print('Contains non-whitespace characters.')

輸出

All whitespace characters
Contains non-whitespace characters

相關用法


注:本文由純淨天空篩選整理自 Python String isspace()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。