【问题标题】:python check string for emptieness - is this the elegant way [duplicate]python检查字符串是否为空-这是优雅的方式吗?
【发布时间】:2013-09-11 08:18:33
【问题描述】:
if var is not None and var !="" and var !=" ":
   # todo

我可以这样写吗?:

if var: 
   # todo

var 只是 String 类型。

【问题讨论】:

  • @aug 不是因为 OP 也希望空格也算作空字符串。

标签: python


【解决方案1】:

如果你想过滤掉只有空格的字符串(" "):

if var and var.strip():
    # ...

因为如果用作谓词,包含空格的字符串将被评估为 True:

>>> bool("")
False

>>> bool("  ")
True

【讨论】:

  • 我认为if var.strip(): 是等价的。
  • @ShashankGupta:如果var 可能是None,则不会。
  • @MartijnPieters 好点 :)
  • 虽然很明显如果' 'only 应该被认为是假的空白字符串,而' ' * 2'\t' 应该被认为是真的,如代码中的问题,那么答案就不同了:-)
猜你喜欢
  • 2010-09-26
  • 2020-08-11
  • 1970-01-01
  • 2013-08-13
  • 2015-06-12
  • 1970-01-01
  • 2015-06-05
  • 1970-01-01
相关资源
最近更新 更多