📜  Python String isspace() 方法

📅  最后修改于: 2022-05-13 01:55:25.883000             🧑  作者: Mango

Python String isspace() 方法

Python String isspace()是用于字符串处理的内置方法。如果字符串中的所有字符都是空白字符,则 isspace() 方法返回“True”,否则返回“False”。此函数用于检查参数是否包含所有空格字符,例如:

  • ' ' - 空间
  • '\t' - 水平制表符
  • '\n' - 换行符
  • '\v' - 垂直制表符
  • '\f' - 饲料
  • '\r' - 回车

示例 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())


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)


输出:

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