How to Check if a Python String Is Empty?

python

There are a few ways to check if a Python string is empty. Here are three common methods:

Method 1: Using len()

You can use the built-in len() function to check the length of a string. An empty string has a length of zero, so if the length of the string is zero, it means the string is empty.

Example:

my_str = ''

if len(my_str) == 0:
    print('The string is empty')
else:
    print('The string is not empty')

Output:

The string is empty

Method 2: Using not operator

You can use the not operator to check if a string is empty. The not operator returns True if the string is empty and False if it's not.

Example:

my_str = ''

if not my_str:
    print('The string is empty')
else:
    print('The string is not empty')

Output:

The string is empty

Method 3: Using == operator

You can also use the == operator to check if a string is empty. You compare the string to an empty string using the == operator, and if they are equal, it means the string is empty.

Example:

my_str = ''

if my_str == '':
    print('The string is empty')
else:
    print('The string is not empty')

Output:

The string is empty

Latest Questions

python How to Fix ""zsh: command not found: python" Error on MacOS X? python How to Fix "xlrd.biffh.XLRDError: Excel xlsx file; not supported" Error in Pandas? python How to Remove All Whitespace From a Python String?