当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。