isspace()

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 )

Handling Mixed Characters

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.

Handling Edge Cases

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.

Use Cases for isspace()

Trimming Whitespace

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")

More Examples

Whitespace in File Parsing

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.


All String methods


Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer