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


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

Python String isspace() 是用於字符串處理的 內置 方法。如果字符串中的所有字符都是空白字符,則 isspace() 方法返回 “True”,否則返回 “False”。此函數用於檢查參數是否包含所有空格字符,例如:

  • ' ' - 空間
  • ‘\t’ - 水平標簽
  • ‘\n’ - 換行符
  • ‘\v’ - 垂直製表符
  • '\f' - 飼料
  • '\r' - 回車
用法:

string.isspace()

參數:

isspace() 不帶任何參數



返回值:

  1. 真的- 如果字符串中的所有字符都是空白字符。
  2. 錯誤的- 如果字符串包含 1 個或多個非空白字符。

例子1

Input:string = 'Geeksforgeeks'
Output:False

Input:string = '\n \n \n'
Output:True

Input:string = 'Geeks\nFor\nGeeks'
Output:False

Python3


# Python code for implementation of isspace()
   
# checking for whitespace characters
string = 'Geeksforgeeks'
  
print(string.isspace())
   
# checking if \n is a whitespace character
string = '\n \n \n'
  
print(string.isspace())
  
string = 'Geeks\nfor\ngeeks'
print( string.isspace())

輸出:

False
True
False

示例 2:實用應用

給定 python 中的字符串,計算字符串中空格字符的數量。

Input:string = 'My name is Ayush'
Output:3

Input:string = 'My name is \n\n\n\n\nAyush'
Output:8

算法:

  1. 逐個字符地遍曆給定的字符串直到其長度,檢查該字符是否為空白字符。
  2. 如果是空白字符,則將計數器加 1,否則遍曆到下一個字符。
  3. 打印計數器的值。

Python3


# Python implementation to count whitespace characters in a string
# Given string
# Initialising the counter to 0
string = 'My name is Ayush'
count=0
   
# Iterating the string and checking for whitespace characters
# Incrementing the counter if a whitespace character is found
# Finally printing the count
for a in string:
    if (a.isspace()) == True:
        count+=1
print(count)
  
string = 'My name is \n\n\n\n\nAyush'
count = 0
for a in string:
    if (a.isspace()) == True:
        count+=1
print(count)

輸出:

3
8




相關用法


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