Python 字串 isspace() 方法



python 字串isspace() 方法用於檢查字串是否僅由空白字元組成。如果輸入字串中的所有字元都是空白字元,並且至少有一個字元,則此方法返回 True。否則,它返回 False。

如果 Unicode 字元資料庫中字元的通用類別為 Zs(“分隔符,空格”),或者其雙向類別為 WS、B 或 S 之一,則該字元為空白字元。

讓我們在下一節中更詳細地瞭解此方法。

語法

以下是 python 字串isspace() 方法的語法:

str.isspace()

引數

python 字串isspace() 方法不包含任何引數。

返回值

如果字串中的所有字元都是空白字元,並且至少有一個字元,則此方法返回 True,否則返回 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
python_strings.htm
廣告