Most elegant way to check if the string is empty i

2019-01-01 04:38发布

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.

22条回答
何处买醉
2楼-- · 2019-01-01 04:44

How about this? Perhaps it's not "the most elegant", but it seems pretty complete and clear:

if (s is None) or (str(s).strip()==""): // STRING s IS "EMPTY"...
查看更多
几人难应
3楼-- · 2019-01-01 04:45

Either the following

foo is ''

or even

empty = ''
foo is empty
查看更多
与君花间醉酒
4楼-- · 2019-01-01 04:46

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.

查看更多
美炸的是我
5楼-- · 2019-01-01 04:46

I find hardcoding(sic) "" every time for checking an empty string not as good.

Clean code approach

Doing this: foo == "" is very bad practice. "" is a magical value. You should never check against magical values (more commonly known as magical numbers)

What you should do is compare to a descriptive variable name.

Descriptive variable names

One may think that "empty_string" is a descriptive variable name. It isn't.

Before you go and do empty_string = "" and think you have a great variable name to compare to. This is not what "descriptive variable name" means.

A good descriptive variable name is based on its context. You have to think about what the empty string is.

  • Where does it come from.
  • Why is it there.
  • Why do you need to check for it.

Simple form field example

You are building a form where a user can enter values. You want to check if the user wrote something or not.

A good variable name may be not_filled_in

This makes the code very readable

if formfields.name == not_filled_in:
    raise ValueError("We need your name")

Thorough CSV parsing example

You are parsing CSV files and want the empty string to be parsed as None

(Since CSV is entirely text based, it cannot represent None without using predefined keywords)

A good variable name may be CSV_NONE

This makes the code easy to change and adapt if you have a new CSV file that represents None with another string than ""

if csvfield == CSV_NONE:
    csvfield = None

There are no questions about if this piece of code is correct. It is pretty clear that it does what it should do.

Compare this to

if csvfield == EMPTY_STRING:
    csvfield = None

The first question here is, Why does the empty string deserve special treatment?

This would tell future coders that an empty string should always be considered as None.

This is because it mixes business logic (What CSV value should be None) with code implementation (What are we actually comparing to)

There needs to be a separation of concern between the two.

查看更多
浪荡孟婆
6楼-- · 2019-01-01 04:46

If you just use

not var1 

it is not possible to difference a variable which is boolean False from an empty string '':

var1 = ''
not var1
> True

var1 = False
not var1
> True

However, if you add a simple condition to your script, the difference is made:

var1  = False
not var1 and var1 != ''
> True

var1 = ''
not var1 and var1 != ''
> False
查看更多
还给你的自由
7楼-- · 2019-01-01 04:47

I once wrote something similar to Bartek's answer and javascript inspired:

def isNotEmpty(s):
    return bool(s and s.strip())

Test:

print isNotEmpty("")    # False
print isNotEmpty("   ") # False
print isNotEmpty("ok")  # True
print isNotEmpty(None)  # False
查看更多
登录 后发表回答