检查空字符串的Pythonic方法

时间:2019-06-25 02:16:59

标签: python

我有一个简单的函数,它接受2个参数,并用第二个参数减去第一个参数。

该函数还应该执行以下操作:

  • 检查两个参数都不为空,无或为空字符串
  • 检查两个参数均为数字
  • 将字符串中的数字转换为整数(例如'7'-> 7)

如果将空字符串作为参数之一传入,则会收到错误消息。如何以pythonic方式编写此函数而又不添加对空字符串的附加检查?


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'

错误:

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

2 个答案:

答案 0 :(得分:1)

使用try / except这样的方法比使用构建块来处理您可能遇到的每种情况要好。

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

答案 1 :(得分:0)

您可以使用if语句检查空字符串。

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

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

下面是示例输出:

>>> 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