【发布时间】: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