数据STUDIO

不要再这样的判断空字符串了!

Image

Image
Image

我们要编写一个程序:

  • 提示用户输入一个单词
  • ERROR如果用户输入的是空字符串则打印
  • nice!如果用户输入非空字符串则打印

以下是一些有效的代码:

string = input()
if len(string) > 0:
    print("nice!")

但这不是最理想的代码,因为它不是 Python 风格的。

编写此代码的 Pythonic 方式

string = input()
if string:
    print("nice!")

这与上面的代码完全相同,但对于较新的 Python 学习者来说可能看起来不直观。

到底发生了什么事?

来谈谈真值和假值。

  • 如果我们执行 bool(var),值 var 的值为 True,那么它就是真值。
  • 如果我们执行 bool(var), 值 var 的值为 False,那么它就是假值。

例如,"apple"  是真值,我们可以通过打印 bool("apple") 来验证。如果在 Python 中使用一个真值作为条件,它会自动返回 True。

if "apple":
    print("this will print")

print(bool("apple")) # True

空字符串""为假值,我们可以通过打印bool("")来验证它。如果在 Python 中使用假值作为条件,它会自动返回 False。

if "":
    print("this wont print")
print(bool("")) # False

常见的假值

  • 空字符串""
  • 零(int)0
  • 零(float)0.0
  • 空集合,例如 list/tuple/dict[] {} ()
  • None

常见的真值

  • 长度为 1 或以上的非空字符串
  • 非零数字(负数也是真值)
  • 非空集合,例如:list/tuple/dict[1, 2] {1: 2}(1, 3)
  • 对象

回到主题

这里,请注意,我使用的if string: 而不是if len(string) > 0

string = input()
if string:
    print("nice!")
else:
    print("ERROR")

这样做的原因是:

  • 如果string为空,则它是一个假值,其值为 False。
  • 如果string不为空,则它是真实值,其值为 True。

为什么我们选择这样编写代码?

  • 更优雅、更简洁
  • 它是编写 Python 代码的更有 Python 风格 的方法
  • 它是业界广泛接受的 Python 代码编写方式

其他数据类型

整数:

if 1:
    print("this will print as 1 is truthy")
if 0:
    print("this wont print as 0 is falsy")

浮点数:

if 10.5:
    print("this will print as 10.5 is truthy")

if 0.0:
    print("this wont print as 0.0 is falsy")

集合,例如列表、元组、字典

if [1, 2, 3]:
    print("this will print as [1, 2, 3] is truthy")

if []:
    print("this wont print as [] is falsy")

    if {1:2, 100: 3}:
    print("this will print as {1:2, 100:3} is truthy")

if {}:
    print("this wont print as {} is falsy")

🏴‍☠️宝藏级🏴‍☠️ 原创公众号『数据STUDIO』内容超级硬核。公众号以Python为核心语言,垂直于数据科学领域,包括可戳👉Python|MySQL|数据分析|数据可视化|机器学习与数据挖掘|爬虫 等,从入门到进阶!

长按👇关注- 数据STUDIO -设为星标,干货速递ImageImage