简体   繁体   中英

How do I add “and” inbetween the last integers

I have this code:

def guess_index(guess, word):   
    word2 = list(word)
    num = word.count(guess)+1
    count = 0
    x = []
    for i in range(0,num):
        try:
            count += 1
            y = word2.index(guess)
            x.append(y+count)
            del(word2[y])
        except ValueError:
            break
    z = ",".join(str(i)for i in x)

return "The character you guessed is number %s in the word you have to guess" % (z)

I would like for the last integers in my z string to have an and in them, so it would print like, The character you guessed is number 1,2,3 and 7 in the word you have to guess . Any pointers in the right direction would be really helpful. Thank You.

You can slice x to leave out the last one, then add it manually. Be sure to check if the list is empty or only has one element because of how slicing works with negative indices:

z = (','.join(str(i) for i in x[:-1]) + " and " + str(x[-1])) if len(x) > 1 else '' if len(x) == 0 else str(x[0])

Example:

>>> x = [1, 2, 3, 7]
>>> z = (','.join(str(i) for i in x[:-1]) + " and " + str(x[-1])) if len(x) > 1 else '' if len(x) == 0 else str(x[0])
>>> z
'1,2,3 and 7'

Although I highly recommend adding an oxford comma and using some spaces, just to be pretty:

z = (', '.join(str(i) for i in x[:-1]) + ", and " + str(x[-1])) if len(x) > 1 else '' if len(x) == 0 else str(x[0])

This can be written out as:

if len(x) > 1:
    z = ', '.join(str(i) for i in x[:-1]) + ", and " + str(x[-1])
elif len(x) == 1:
    z = str(x[0])
else:
    z = ''

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