Skip to content
Related Articles

Related Articles

Improve Article

Python String isspace() Method

  • Difficulty Level : Basic
  • Last Updated : 12 Aug, 2021

Python String isspace() is a built-in method used for string handling. The isspace() method 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:

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

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.

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

Output: 

False
True
False

Example 2: Practical Application

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

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 up to its length, check if the 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.

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)

Output: 

3
8



My Personal Notes arrow_drop_up
Recommended Articles
Page :