sentence = input("Please enter a sentence excluding punctuation")
chars = set('0123456789!"£$%^&*()_-+={}[];:@#~/?.,<>\|`¬')
while any((c in chars) for c in sentence):
sentence = input("Please enter another sentence excluding punctuation")
else:
print('Your sentence is fine')
sentence = sentence.upper()
locateword = input ("Enter a word from the inputted sentence to locate")
locateword=locateword.upper()
while locateword not in sentence:
locateword = input ("Enter another word from the inputted sentence to locate")
locateword=locateword.upper()
else:
print ("Your word is fine")
sentence = sentence.split()
for (position,words) in enumerate(sentence):
if (locateword in words):
print ("The position of your word is",position+1)
This code finds the position of an inputted word in the inputted sentence. However when a single character is the word to be located, the code finds the position of the word that contains that character, how could I fix this code so that this doesn't happen? For example, when the sentence is "I like football" and the word is "ball", the position returned is 3 as "ball" is found in "football", but I do not want this to happen.
试试这个:
在你分开你的句子之前用这个
或者
在你再次分开你的句子之前做这个
\b
表示regex中的单词边界。所以一个字也听不到也许:
尽管这不是你的问题,但检查字符串是否包含字母数字字符的更好方法是:
完整代码:
在您的代码中,因为
sentence
已经被拆分,所以if (locateword in words)
将在football
中搜索ball
,而不是在["I", "like", "football"]
中搜索你可以试试:
相关问题 更多 >
编程相关推荐