错误跟踪:
C:\Users\Abhi.Abhi-PC\Desktop\PYE>ex25ex.py Traceback (most recent
call last): File "C:\Users\Abhi.Abhi-PC\Desktop\PYE\ex25ex.py", line
41, in <module> print_last_word(sentence) File
"C:\Users\Abhi.Abhi-PC\Desktop\PYE\ex25ex.py", line 17, in
print_last_word word = words.pop(1) AttributeError: 'str' object
has no attribute 'pop'
这是代码
def break_words(stuff):
"""This function will break up words for us."""
words = stuff.split()
return words
def sort_words(words):
"""Sorts the words."""
return sorted(words)
def print_first_word(words):
"""Prints the first word after popping it off."""
word = words.pop(0)
print word
def print_last_word(words):
"""Prints the last word after popping it off."""
word = words.pop(1)
print word
def sort_sentence(sentence):
"""Takes in a full sentence and returns the sorted words."""
words = break_words(sentence)
return sort_words(words)
def print_first_and_last(sentence):
"""Prints the first and last words of the sentence."""
words = break_words(sentence)
print_first_word(words)
print_last_word(words)
def print_first_and_last_sorted(sentence):
"""Sorts the words then prints the first and last one."""
words = sort_sentence(sentence)
print_first_word(words)
print_last_word(words)
sentence="island has lush vegetation, area. However, summers are cooler than those abundant."
break_words(sentence)
sort_words(sentence)
print_last_word(sentence)
print_last_word(sentence)
print_first_and_last_sorted(sentence)
print_first_and_last(sentence)
我无法弄清楚问题所在。我正在阅读“如何以艰苦的方式学习 Python”一书。
原文由 Abhishek Kaushik 发布,翻译遵循 CC BY-SA 4.0 许可协议
您的代码的问题在于您忽略了函数的返回值,尤其是
break_words
,并且始终对原始输入进行操作。这将解决问题:还有一个小问题,您应该使用
words.pop(-1)
访问单词列表中的最后一项。您如何从错误消息中识别出问题。异常是一个 AttributeError,指出
'str' object has no attribute 'pop'
。显然,在words.pop(0)
行中, words 是一个字符串,而不是字符串列表,正如变量名所暗示的那样。然后只需快速浏览一下即可了解为什么这个变量是一个字符串:当您使用print_last_word(sentence)
调用函数时,您将原始数据(类型str
)传递给它,而不是预处理后的数据您可能打算传递的数据。