Python String isspace()

Python string isspace() method is a built-in function that returns True if all the characters in a string are whitespace characters. Otherwise, it returns false.

What are whitespace characters in Python?

Characters that are used for spacing are called whitespace characters. For example: tabs, spaces, newline, etc.

The isspace() 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

isspace() Syntax

The syntax of isspace() method is:

string.isspace()

isspace() Parameters

The isspace() method doesn’t take any parameters.

isspace() Return value

The isspace() method returns:

  • True if all characters in the string are whitespace characters
  • False if the string is empty or contains at least one or more non-whitespace character

Example 1: Working with isspace() method

# whitespace characters. returns true
text1 = "\t    "
print(text1.isspace())

# string contains non whitespace
text2= "Hello World"
print(text2.isspace())

# whitespace and returns true
text3= " "
print(text3.isspace())

# empty string and returns false
text4=""
print(text4.isspace())

# whitespace characters returns false
text5= "\t\n\f"
print(text5.isspace())

Output

True
False
True
False
True

Example 2: Program to check if the string has only whitespace characters

# whitespace string
text1 = "\t\n\f"
if(text1.isspace()):
    print("String contains only whitespace characters")
else:
    print("String contains non whitespace characters")

# Non whitespace String
text2= " \t    Hello"
if(text2.isspace()):
    print("String contains only whitespace characters")
else:
    print("String contains non whitespace characters")

Output

String contains only whitespace characters
String contains non whitespace characters
Leave a Reply

Your email address will not be published.

Sign Up for Our Newsletters

Get notified of the best deals on our WordPress themes.

You May Also Like
Python String Find()

Python String find()

Table of Contents Hide find() Syntaxfind() Parametersfind() Return ValueDifference between find() method and index() methodExample 1: find() without any argumentsExample 2: find() with start and end Arguments The Python String…
View Post
Convert Letters To Numbers In Python

Convert Letters to Numbers in Python

Table of Contents Hide Convert Letters to Numbers in PythonUsing ord() MethodUsing list comprehensionConclusion Using the ord() method, we can convert letters to numbers in Python. The ord() method returns…
View Post