How to check if the string is empty?

后端 未结 25 1850
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 14:47

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

if myString == string.empty:

Regardless, what\'s the most elegan

25条回答
  •  误落风尘
    2020-11-22 15:00

    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.

提交回复
热议问题