my_str.isspace()
Returns True if all chars in a string are white space , otherwise returns False
my_str='Welcome to plus2net'
print(my_str.isspace()) # Output is False
my_str=' '
print(my_str.isspace()) # Output is True
my_str=' \n '
print(my_str.isspace()) # Output is True ( presence of line break \n)
my_str=' \t '
print(my_str.isspace()) # Output is True ( presence of tab \t )
my_str=' com '
print(my_str.isspace()) # Output is False ( presence of string )
When a string contains non-whitespace characters, isspace() will return False. Here’s an example:
my_str = " hello"
print(my_str.isspace()) # Output: False
Explanation: This shows that strings with any characters besides whitespace will not satisfy the method.
The method's behavior on edge cases, such as an empty string or newline characters:
my_str = ""
print(my_str.isspace()) # Output: False
my_str = "\n\t"
print(my_str.isspace()) # Output: True
Explanation: Empty strings return False, while strings with only tabs or newlines return True.
isspace() is useful when checking if a string contains only spaces, such as when sanitizing user input in forms:
user_input = " "
if user_input.isspace():
print("Input contains only whitespace")
When processing files line by line, isspace() can help detect lines that are only whitespace:
with open("file.txt", "r") as file:
for line in file:
if line.isspace():
print("Empty line found")
Explanation: Useful in parsing large text files where blank lines are treated differently.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.