我的代码没有显示“找不到匹配项”,为什么?

时间:2018-11-23 19:56:37

标签: python

这是我的代码。 它不打印“找不到匹配项” 我认为这与启动部分的程序有关

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)

2 个答案:

答案 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