How to check if text is “empty” (spaces, tabs, newlines) in Python?

PythonServer Side ProgrammingProgramming

The string can be checked by checking for occurrences of only whitespace characters. We can check if a string contains only whitespace characters using 2 methods. First is using method isspace(). 

example

print('Hello world'.isspace())
print('         '.isspace())

Output

False
True

You can also use regexes for the same result. For matching only whitespace, we can call the re.match(regex, string) using the regex metacharacter \s as follows: "^\s*$". 

example

import re
print(bool(re.match('^\s+$', '  abc')))
print(bool(re.match('^\s+$', '          ')))

Output

False
True
raja
Published on 11-Dec-2017 12:03:35
Advertisements