Open In App

Python String isspace() Method

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Python String 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

Python String isspace() Method Syntax

Syntax: string.isspace()

Returns:

  1. True – If all characters in the string are whitespace characters.
  2. False – If the string contains 1 or more non-whitespace characters.

Python String isspace() Method Example

Python3




string = "\n\t\n"
print(string.isspace())


Output:

True

Example 1:  Basic Intuition of isspace() in Program

Here we will check whitespace in the string using isspace() program.

Python3




# 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




# 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


Last Updated : 18 Aug, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads