Zoran Pandovski
By Zoran Pandovski

How to check for empty space, tab or newline in Python

How to check for empty space, tab or newline in Python

The built-in string method isspace() checks if there are only whitespace characters in the string, otherwise it will return False.

The best use case of this method is to check if the string contains characters as:

  • ‘\n’ - new line
1
2
3
4
5
6
7
mystring = '\n'

mystring.isspace()

>>>True

  • ’ ‘ - whitespace
1
2
3
4
5
6
7
mystring = ' '

mystring.isspace()

>>>True

  • ‘\t’ - tab
1
2
3
4
5
6
7
mystring = '\t'

mystring.isspace()

>>>True

  • ‘\r’ - carriage return
1
2
3
4
5
6
7
mystring = '\r'

mystring.isspace()

>>>True

  • ‘\f’ - form feed
1
2
3
4
5
6
7
mystring = '\f'

mystring.isspace()

>>>True

Or combination:

1
2
3
4
5
6
7
8
9
10
11
12
13
mystring = ' \t'

anotherstring = '\n\t'

mystring.isspace()

anotherstring.isspace()

>>>True

>>>True

Note that isspace() will not return True for ‘’, so always check with not mystring or mystring.isspace().