sentence='ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY'
word=[]
pos=0
choice=''
while choice!='q':
print(sentence)
word=sentence.split(' ')
choice=input('what word do you want to find').upper()
for pos in range(len(word)):
if choice==word[pos]:
print('The word ' + str(choice)+ ' occurs in the ' + str(pos +1) + ' th position ')
if choice not in word:
print("not valid word")
所以,我有这个代码打印我的数组中的单词位置,但是让我们说这个单词处于零位置,例如,我想让它想出单词ASK出现在第一个位置而不是单词ASK发生在第th位置,依此类推,例如nd,rd和th。 任何帮助将不胜感激!
答案 0 :(得分:0)
您可以使用humanize
包,特别是函数humanize.number.ordinal()
完全符合您的要求:
>>> from humanize import number
>>> for i in range(30):
... print(number.ordinal(i))
1st
2nd
3rd
4th
5th
6th
7th
8th
9th
10th
11th
12th
13th
14th
15th
16th
17th
18th
19th
20th
21st
22nd
23rd
24th
25th
26th
27th
28th
29th
对于您的代码,您可以将print()
更改为:
print('The word ' + str(choice)+ ' occurs in the ' + number.ordinal(pos+1) + ' position ')
或者更好,请使用str.format()
:
print('The word {} occurs in the {} position'.format(choice, number.ordinal(pos+1)))
答案 1 :(得分:-1)
你可以使用这样的函数:
def ordinal(n):
if n == 1:
return "first"
elif n == 2:
return "second"
elif n == 3:
return "third"
else:
return str(n)+"th"
将其合并到您的代码中作为练习: - )