Tuesday, 8 May 2018

python - How to check if the string is empty?



Does Python have something like an empty string variable where you can do:



if myString == string.empty:



Regardless, what's the most elegant way to check for empty string values? I find hard coding "" every time for checking an empty string not as good.


Answer



Empty strings are "falsy" which means they are considered false in a Boolean context, so you can just do this:



if not myString:


This is the preferred way if you know that your variable is a string. If your variable could also be some other type then you should use myString == "". See the documentation on Truth Value Testing for other values that are false in Boolean contexts.



No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...