Change language

Python String isspace () and its application

| | |

In Python, isspace () — it is a built-in method used to process strings. The isspace () methods return True if all characters in the string are whitespace, otherwise it returns False. 
This function is used to check if the argument contains all whitespace characters, such as:

  • & # 39; & # 39; — Space
  • & # 39; / t & # 39; — Horizontal tab
  • & # 39; / n & # 39; — Newline
  • & # 39; / v & # 39; — vertical tab
  • & # 39; / f & # 39; — Feed
  • & # 39; / r & # 39; — 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 =’ ’Output: True Input: string =’ Geeks For Geeks ’Output: False 

# Python code to implement isspace ()

  
# whitespace checking

string = ’ Geeksforgeeks’

 

print (string.isspace ())

 
# check if / n is a space character

string = ’’

 

print (string.isspace ())

  

string = ’Geeks for geeks’

print (string.isspace ())

Output:

 False True False 

claim

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

 Input: string = ’My name is Ayush’ Output: 3 Input: string =’ My name is Ayush’ Output: 8 

Algorithm
1. Go through the given line character by character to its length, check if the character is a space. 
2. If it is a whitespace character, increment the counter by 1, otherwise go to the next character. 
3. Print the counter value.

# Python implementation for counting whitespace in a string
# Specified string
# Initialize counter to 0

string = ’My name is Ayush’

count = 0

 
# Line iteration and whitespace checking
# Increment counter if whitespace character is found
# Finally, print the invoice

for a in string:

if (a.isspace ()) = = True :

count + = 1

print (count)

  

string = ’My name is Ayush’

count = 0

for a in string:

if (a.isspace ())   = = True :

count + = 1

print (count)

Output:

 3 8