[英]How do I add “and” inbetween the last integers
我有以下代碼:
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
。 正確方向的任何指示都將非常有幫助。 謝謝。
您可以切片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 = ''
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.