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