我的代码的目的是从用户那里获取一个字符串并变成一个不区分大小写的列表。然后我需要从用户那里获取第二个字符串,然后输出第二个给定字符串的位置。这是我的代码:
UserSentence = input('Enter your chosen sentence: ') #this is where the user inputs their sentence
from string import punctuation #this 'fetches' the punctuation from the string
tbl=str.maketrans({ord(ch):" " for ch in punctuation})
UserSentence = UserSentence.lower().translate(tbl).split()#.split() turns the input sentence into a list,...
#...this will help to identify where a word appears...
#...in the sentence. The .lower() also turns the...
#...string into lowercase so it is not case sensitive.
UserWord = input('Enter a word from the sentence: ')#this is where the user inputs their word from the sentence
UserWord = UserWord.lower()#.lower() is used to make UserWord not case sensitive
for i in range(len(UserSentence)):
if UserSentence (i) == UserWord:
print ('Your chosen word appears in: ')
答案 0 :(得分:1)
要索引序列,您需要使用[]
if UserSentence[i] == UserWord:
如果您正在尝试找到哪个索引(按字词),则可以执行
if UserWord in UserSentence:
print('Your word is located at {}'.format(UserSentence.index(UserWord)))
或类似地
try:
print('Your word is located at {}'.format(UserSentence.index(UserWord)))
except ValueError:
print('Your word is not in the sentence')
答案 1 :(得分:0)
这里有一些错误:
raw_input
作为字符串。在Python 3中input
没问题。maketrans
电话很奇怪您重写和测试过的代码:
from string import punctuation, maketrans
user_sentence = raw_input('Enter a sentence: ')
trans = maketrans("", "")
user_sentence = user_sentence.lower().translate(trans, punctuation).split()
user_word = raw_input('Enter a word from the sentence: ')
user_word = user_word.lower()
if user_word in user_sentence:
print ('Your chosen word appears in the sentence.')