如何在最后一个整数之间添加“和”

时间:2014-03-18 18:10:30

标签: python string

我有这段代码:

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)

我希望我的z字符串中的最后一个整数有一个和它们一样,所以它会像The character you guessed is number 1,2,3 and 7 in the word you have to guess一样打印出来。 任何正确方向的指针都会非常有用。 谢谢。

1 个答案:

答案 0 :(得分:3)

您可以对x进行切片以省略最后一个,然后手动添加。一定要检查列表是空的还是只有一个元素,因为切片如何与负索引一起使用:

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])

示例:

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

虽然我强烈建议添加一个牛津逗号并使用一些空格,但为了漂亮:

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])

这可以写成:

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