简体   繁体   中英

Pythonic way of checking null and empty string

I have a simple function that takes 2 params and subtract the first param with the second param.

The function should also do the following:

  • Check both params are not null, None or empty string
  • Check both params are numeric
  • Convert numbers in string into integer (eg '7' --> 7)

I am getting errors if empty string is passed in as one of the params. How to write this function in a pythonic way without adding additional checks for empty string?


def get_num_diff(first_num, second_num):
  if ((first_num is not None) & (second_num is not None)):
    if (type(first_num) is str):
      first_num = int(first_num)
    if type(second_num) is str:
      second_num = int(second_num)
    return first_num - second_num
  else:
    return 'NA'

Error:

invalid literal for int() with base 10: ''

Something like this is better handled using try/except rather than building blocks to handle every case you might encounter.

def get_num_diff(first_num, second_num):
    try:
        first_num = int(first_num)
        second_num = int(second_num)
    except (ValueError, TypeError):
        return 'NA'
    return first_num - second_num

You can check for an empty string with an if statement.

test = ""
if not test:
    print("This test string is empty")

test = "Not Empty"
if test:
    print("This test string is not empty")

Below is example output:

>>> test = ""
>>> if not test:
...     print("This test string is empty")
... 
This test string is empty
>>> test = "Not Empty"
>>> if test:
...     print("This test string is not empty")
... 
This test string is not empty

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM