在Python中,isspace()是用於字符串處理的內置方法。如果字符串中的所有字符均為空格字符,則isspace()方法返回“True”,否則,返回“False”。此函數用於檢查參數是否包含所有空格字符,例如:
- ' ' - 空間
- ‘\ t’-水平標簽
- ‘\ n’-換行符
- ‘\ v’-垂直標簽
- ‘\ f’-提要
- ‘\ r’-回車
用法:
string.isspace() 參數: isspace() does not take any parameters 返回: 1.True- If all characters in the string are whitespace characters. 2.False- If the string contains 1 or more non-whitespace characters.
例子:
Input:string = 'Geeksforgeeks' Output:False Input:string = '\n \n \n' Output:True Input:string = 'Geeks\nFor\nGeeks' Output:False
# 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
Application
給定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.打印計數器的值。
# 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
相關用法
- Python string isalpha()用法及代碼示例
- Python string isdigit()用法及代碼示例
- Python string isnumeric()用法及代碼示例
- Numpy string isspace()用法及代碼示例
- Python Pandas Series.str.isspace()用法及代碼示例
注:本文由純淨天空篩選整理自AyushSaxena大神的英文原創作品 Python String isspace() and its application。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。