How can I check if a string is empty in Python?

How can I check if a string is empty in Python? Is there a built-in variable like string.empty that represents an empty string, allowing for a check like if myString == string.empty? If not, what is the most elegant way to check for an empty string without hardcoding "" each time?

Hey Isha,

To help you with this, you can use the len() function. This approach checks the string length using the len() function. If the length is 0, it means the string is empty.

myString = ""
if len(myString) == 0:
    print("String is empty")

Hey Devan

Your answer is optimized, but this method works like magic.

  • Using the not operator: In Python, empty sequences (like strings, lists, and dictionaries) are considered “falsy” when used in a boolean context. The not operator checks if the string is “falsy”, which is the case for an empty string.
myString = ""
if not myString:
    print("String is empty")

Hey Isha,

I agree with @babitakumari, but you can also use string formatting: This method directly compares the string to an empty string ". If the string is empty, the comparison will return True, indicating that the string is indeed empty.

myString = ""
if myString == "":
    print("String is empty")