How to check if a string is empty?
How to check if a string is empty in Python? There are several ways to check if a string is empty in Python. While this sounds like an easy task, it's actually not so trivial.
For example, a string containing only spaces is considered empty but has still a non-zero length. Every space is counted as one character by the len() function.
Option 1: len() function
The len() function returns the length of a string, that is the count of characters. As mentioned above, spaces are counted like regular characters.
# check if string is empty
myString = ''
print(len(myString))
The length of the string is 0, therefore the string is empty.
0
The check if spaces are
____
myString = ''
if not myString:
print('myString is empty')
myString is empty
How to check if string is not empty:
myString = 'not empty'
if myString:
print('myString is not empty')
myString is not empty