lllluuukke
lllluuukke

Reputation: 1342

Which way to determine empty string is better?

In my code, I need to test whether or not a string is empty for millions of times. The question is, which way is better/faster: if str == '' or if len(str) == 0. If there's better ways to do this, please share. Any help appreciated.

Upvotes: 1

Views: 117

Answers (1)

Niklas B.
Niklas B.

Reputation: 95338

Please don't name your variables str, as this is the name of a built-in function.

So if you can be sure that s is a string (which hopefully is the case), you can just use

if not s:
  # s is the empty string

This should be the preferred way of doing such a check. It also works for lists, sets and dicts. Performance-wise, there's probably no noticeable difference, but you can of course measure that to be sure.

Upvotes: 6

Related Questions