AppDividend
Latest Code Tutorials

Python String isspace: Complete Guide

The String isspace()  function is used to check if the argument contains all whitespace characters such as:

  1. ‘ ‘ – Space
  2. ‘\t’ – Horizontal tab
  3. ‘\n’ – Newline
  4. ‘\v’ – Vertical tab
  5. ‘\f’ – Feed
  6. ‘\r’ – Carriage return

Python String isspace()

The string isspace() is a built-in Python method that tells us if the given string contains only space characters or not. The isspace() method returns true if all the characters of the string are space and return false in all other cases.

There are different types of whitespace characters such as ‘\n’- Newline, ‘ ‘-space, ‘\t’- Horizontal tab, and many more. By the above different types of whitespace, we can categorize if our string contains only whitespace or not, which we can check by using the isspace() method.

Syntax

string.isspace()

Here string is the string variable, which is to be checked if it contains all its characters are whitespace or not.

Parameters

The String.isspace() method doesn’t contain any parameters and throws an error if any parameter is passed.

Return Value

The method returns true if all the characters are whitespaces in the string and false in all other cases.

Example programs on string isspace() method

Example1: Write a program to show the working or isspace() method.

# app.py

h1 = "  "
h2 = "Hello    Boy"
h3 = "\n\n\t\n\n"
h4 = "HelloGirl"
print(h1.isspace())
print(h2.isspace())
print(h3.isspace())
print(h4.isspace())

Output

python3 app.py
True
False
True
False

Example2: Write a program to check if two strings contain only whitespace characters. Print “Yes” if true and “No” if false.

# app.py

h1 = "  "
h2 = "\t"
if(h1.isspace() and h2.isspace()):
    print("YES")
else:
    print("NO")

Output

python3 app.py
YES
Example 3: We can calculate the total occurrences of spaces in a string.
# app.py

string = 'KGF movie starring\n\n\n\n\n\n Yash'
count = 0
for a in string:
    if (a.isspace()) == True:
        count += 1
print(count)

Output

python3 app.py
9

Finally, Python String isspace() Method Example is over.

See also

Python string istitle()

Python string rsplit()

Python string rindex()

Python string rfind()

Python string partition()

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.