Floofk
Floofk

Reputation: 113

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.

Upvotes: 0

Views: 54

Answers (1)

2rs2ts
2rs2ts

Reputation: 11026

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 = ''

Upvotes: 3

Related Questions