Python String isspace() and its application

In Python, isspace() is a built-in method used for string handling. The isspace() methods returns “True” if all characters in the string are whitespace characters, Otherwise, It returns “False”.
This function is used to check if the argument contains all whitespace characters such as :

  • ‘ ‘ – Space
  • ‘\t’ – Horizontal tab
  • ‘\n’ – Newline
  • ‘\v’ – Vertical tab
  • ‘\f’ – Feed
  • ‘\r’ – Carriage return

Syntax :

string.isspace()
Parameters:
isspace() does not take any parameters
Returns :
1.True- If all characters in the string are whitespace characters.
2.False- If the string contains 1 or more non-whitespace characters.

Examples:

Input : string = 'Geeksforgeeks'
Output : False

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

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

edit
close

play_arrow

link
brightness_4
code

# 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())

chevron_right


Output:

False
True
False

Application

Given a string in python, count number of whitespace characters in the string.
Example :

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

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

Algorithm
1. Traverse the given string character by character upto its length, check if character is a whitespace character.
2. If it is a whitespace character, increment the counter by 1, else traverse to the next character.
3. Print the value of the counter.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


Output:

3
8


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.