【问题标题】:How can python identify empty strings in a list?python如何识别列表中的空字符串?
【发布时间】:2021-11-23 10:21:45
【问题描述】:

我正在学习创建一个“if”语句块来检查某些条件,我希望它们能够识别列表中是否包含空引号。

例如:

favourite_fruit = []

if len(favourite_fruits) == 0:
    print('Fruits are an important part of one's diet')
###This code works which is great as long as the list is empty in terms of it's length.

如果列表不为空,并且其中包含类似“苹果”的内容,但缺少“日期”等另一种水果,那么我会告诉它说:

if 'dates' not in favourite_fruit and len(favourite_fruit) != 0:
    print ('Have you tried Dates? They are high in fibre, a good source of which, can help prevent constipation by promoting bowel movements.') 

但问题是如果我输入:

favourite_fruit = ['']

此列表的长度为 1,但其中没有任何内容,因此它将打印出日期报价,而不是“水果很重要”报价。

有没有办法让 python 识别列表中实际上没有写入任何内容?

我几乎是初学者,所以我还在学习中

这是我尝试过的:

favourite_fruit = ['']

if 'dates' not in favourite_fruit and len(favourite_fruit) != 0 and favourite_fruit != "" and favourite_fruit != "\"\"" and favourite_fruit != '' and favourite_fruit != '\'\'':
    print ('Have you tried Dates? They are high in fibre, a good source of which, can help prevent constipation by promoting bowel movements.')

但还是不行。

【问题讨论】:

  • 你为什么要把空字符串放在列表中?
  • favourite_fruit != ['']
  • "这个列表的长度是 1 但里面什么都没有" 是的,里面有的东西。 str 对象。因此为什么它的长度不是 0

标签: python list if-statement conditional-statements is-empty


【解决方案1】:

想知道为什么列表中有空字符串。

无论如何,假设您想忽略空字符串,您可以先过滤您的列表。在 Python 中,这通常通过以下语法实现,称为列表推导:

favourite_fruit = [f for f in favourite_fruit is f != ""]

[''] 变为 [](空列表),['apple', ''] 变为 ['apple'],等等。你明白了。

旁注:在Python中,非空列表为真,空列表为假,所以if len(favourite_fruits) == 0可以写成if favourite_fruits

【讨论】:

  • 我想你的意思是if favourite_fruit
  • 另外,favourite_fruit = ['']从不被视为空列表。通过运行该列表推导,您可以用一个实际上为空的列表覆盖原始列表。
  • 当然。这才是重点。但解释不清楚。让我换个说法。
  • “我想你的意思是如果 favourite_fruit。”确实。急版。
【解决方案2】:

有没有办法让 python 识别列表中实际上没有写入任何内容?

空字符串为假,因此您需要做的就是检查any 中的favourite_fruit 是否为真。

any([])         => False
any([''])       => False
any(['dates'])  => True

【讨论】:

  • @Pranav 谢谢,我猜,虽然请不要让它看起来像我使用那些可恶的词。
  • Falsy/truthy 与 false/true 不同。我删除了对不正确信息的支持。这些是实际术语,不是我编造的google.com/search?q=falsy+truthystackoverflow.com/q/39983695/843953
  • @PranavHosangadi 你是那个信息不正确的人。 true/false 是 Python 术语中的正确术语,请查看文档,例如 here 或任何其他讨论布尔值的地方。 像你这样的人说 falsy/truthy 的意思是一样的,只是 Python 中的正确术语。
  • 我第二个@PranavHosangadi。 Falsy 通常用于消除bool(a) is Falsea is False 之间的歧义。说[] is False 是模棱两可的。
  • 一个被考虑 True 的对象与它实际上是 True 不同。例如,'' == False 给出False。空序列不是False,它们被考虑 False,这就是像truthy/falsy这样的术语出现的全部原因,而“空字符串是false" 可能会产生误导。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-06
  • 2014-05-08
  • 2011-05-28
  • 2023-02-22
  • 2020-03-30
  • 1970-01-01
相关资源
最近更新 更多