2015-12-07 47 views
-2

我的代码的目的是从用户那里获取一个字符串,并将其转换为不区分大小写的列表。然后,我需要从用户那里吸取第二个字符串,然后输出第二个给定字符串的位置。这是我的代码:如何调试我的Python代码?

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: ') 
+2

“需要帮助调试我的代码,请” - 告诉我们,什么是错的。 – hlt

+0

投票结束,因为没有MCVE。 – halfer

回答

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') 
0

几个错误在这里:

  1. 如果您使用Python 2,请使用raw_input作为字符串。在Python 3中input没问题。
  2. 你的maketrans电话很奇怪
  3. 查找一个单词是否在列表中,你不需要任何循环或自己的比较。 Python可以为你做到这一点。
  4. 请坚持PEP0008。它告诉你如何格式化你的代码,以便阅读。

你的改写和测试代码:

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.') 
+1

*“使用raw_input作为字符串。”*自从Python 3.x以来,这仅仅在2.x中才是真实的 – CoryKramer