Tuesday 21 September 2021

Python: Check whether string contain only whitespaces or not

Strings in python provide ‘isspace’ method, which return True, if the string contains only whitespace characters. Following are treated as whitespace characters.

 

a.   ' ' – Space

b.   '\t' – Horizontal tab

c.    '\n' – Newline

d.   '\v' – Vertical tab

e.   '\f' – Feed

f.     '\r' – Carriage return

 

string_whitespace_check.py

str1 = '   '
str2 = '\t\n\v\f\r'
str3 = ' hello '

print('is str1 contain only spaces', str1.isspace())
print('is str2 contain only spaces', str2.isspace())
print('is str3 contain only spaces', str3.isspace())

Output

is str1 contain only spaces True
is str2 contain only spaces True
is str3 contain only spaces False

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment