简体   繁体   English

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

[英]My code doesn't print ''No matches found'', why?

This is my code. 这是我的代码。 It doesn't print ''No matches found'' I think that it has to do with the section start program 它不打印“未找到匹配项”,我认为这与节开始程序有关

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)

str.split returns a list not a string . str.split返回一个list而不是string Test your value using truthiness instead: 使用真实性测试您的价值:

similarities = scores_and_similarities.split(',')
if not similarities  # better than if similarities == []
    print('\tNo matches found')

note that str.split returns an empty list just when the input string is empty. 请注意,仅当输入字符串为空时, str.split返回一个空列表。 So you could test 所以你可以测试

if not scores_and_similarities:
   print('\tNo matches found')
else:
   # split and process

although I suspect that you're expecting str.split to return empty list if string doesn't contain a comma but it's not: 尽管我怀疑您期望str.split在字符串不包含逗号的str.split下返回空列表,但事实并非如此:

>>> ''.split(",")
>>> []
>>> 'iii'.split(",")
['iii']

so maybe you want to test if , is in the string (note: testing if splitted string has 1-length does the same: 因此,也许您想测试字符串中是否包含, (请注意:测试拆分后的字符串是否具有1个长度是否相同:

if ',' not in scores_and_similarities:
   print('\tNo matches found')

This is because after the split it returns empty list [] not an empty string '' . 这是因为在拆分之后,它返回空列表[]而不是空字符串''

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM