Python String isspace() Method



Python String isspace() Method

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:

 

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

Last Updated on March 1, 2022 by admin

Leave a Reply

Your email address will not be published. Required fields are marked *

Recommended Blogs