在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