简体   繁体   中英

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 . 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. 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:

>>> ''.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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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