这是我的代码。 它不打印“找不到匹配项” 我认为这与启动部分的程序有关
scores_and_similarities = "somestring" # value can be empty
similarities = scores_and_similarities.split(',')
if similarities == '':
print('\tNo matches found')
for similarity in similarities:
print('\t%s' % similarity)
答案 0 :(得分:2)
str.split
返回list
而不是string
。改为使用真实性测试您的价值:
similarities = scores_and_similarities.split(',')
if not similarities # better than if similarities == []
print('\tNo matches found')
请注意,str.split
仅在输入字符串为空时返回空列表。这样您就可以测试
if not scores_and_similarities:
print('\tNo matches found')
else:
# split and process
尽管我怀疑您期望str.split
在字符串不包含逗号但不包含逗号的情况下返回空列表。
>>> ''.split(",")
>>> []
>>> 'iii'.split(",")
['iii']
所以也许您想测试字符串中是否,
(注意:测试分割后的字符串是否具有1长度也可以做到这一点:
if ',' not in scores_and_similarities:
print('\tNo matches found')
答案 1 :(得分:0)
这是因为拆分后它返回空列表[]
,而不是空字符串''
。
scores_and_similarities = "somestring" # value can be empty
similarities = scores_and_similarities.split(',') # empty list is returned
if similarities == '': # [] is not equal to ''
print('\tNo matches found')
for similarity in similarities:
print('\t%s' % similarity) # so answer is this