Python 如何向数组中的单词添加数字后缀
所以,我得到了这个代码,它打印了我数组中的单词位置,但假设单词在零位置,例如Ask,我希望它能找到单词Ask出现在第一位置,而不是单词Ask出现在第四位置,等等,例如nd,rd和th。Python 如何向数组中的单词添加数字后缀,python,Python,所以,我得到了这个代码,它打印了我数组中的单词位置,但假设单词在零位置,例如Ask,我希望它能找到单词Ask出现在第一位置,而不是单词Ask出现在第四位置,等等,例如nd,rd和th。 任何帮助都将不胜感激 您可以使用如下函数: 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':
任何帮助都将不胜感激 您可以使用如下函数:
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")
将其合并到您的代码中只是一个练习:-)您可以使用该软件包,特别是函数humanize.number.ordinal()
完全满足您的需要:
def ordinal(n):
if n == 1:
return "first"
elif n == 2:
return "second"
elif n == 3:
return "third"
else:
return str(n)+"th"
对于您的代码,您可以将print()
更改为:
>>> 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
或者更好地使用str.format()
:
那么重复单词呢?是的,它会说单词ask出现在第一个位置和第十个位置使用dict并将每个单词的索引存储在列表中作为值,然后在dict中进行查找,这对python来说是非常新的,我不太确定我将如何做。很抱歉给您带来不便。这不是您要查找的内容(然后从该位置的单词创建子字符串)?谢谢您的帮助。我如何在字符串中打印它?
print('The word ' + str(choice)+ ' occurs in the ' + number.ordinal(pos+1) + ' position ')
print('The word {} occurs in the {} position'.format(choice, number.ordinal(pos+1)))