Python AttributeError: 'str' object has no attribute 'pop' Learnpythonthehardway

Python AttributeError: 'str' object has no attribute 'pop' Learnpythonthehardway

我有这个错误的持续问题,我试图解决这个问题,因为教程告诉我修复这个代码。大多数代码都是拼写和数学错误,但是我无法解决这个 AttributeError。

教程站点:https://learnpythonthehardway.org/book/exercise26.txt

这是回溯错误:Traceback(最近调用最后):

File "C:\Python34\ex26.py", line 74, in print_first_word(sentence) File "C:\Python34\ex26.py", line 10, in print_first_word word = words.pop(0)

AttributeError: 'str' object has no attribute 'pop'

我必须修复教程代码作为测试的代码:

def break_words(stuff):
    words = stuff.split(' ')
    return words

def sort_words(words):
    return sorted(words)

def print_first_word(words):
    word = words.pop(0)
    print(words)

def print_last_word(words):
    word = words.pop(-1)
    print(word)

def sort_sentence(sentence):
    words = break_wrods(sentence)
    return sort_words

def print_first_and_last(sentence):
    words = break_words(sentence)
    print_first_word(words)
    print_last_word(words)
    return words

def print_first_and_last_sorted(sentence):
    words = sort_sentence(sentence)
    print_first_word(words)
    print_last_word(words)
    return words

print("Let's practice everything.")
print("You\'d need to know \' bout escapes with \ that do \n newlines and \t tabs.")

poem = """
\tThe lovely world with logic
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explaination
\n\twhere there is none.
"""

print("-" * 10)
print(poem)
print("-" * 10)

five = 10 - 2 + 3 - 5
print("This should be five: %s " % five)

def secret_formula(started):
    jelly_beans = started * 100
    jars = jelly_beans / 1000
    crates = jars / 100
    return jelly_beans, jars, crates

start_point = 10000

beans, jars, crates = secret_formula(start_point)

print("With a starting point of: %d " % start_point)
print("We'd have %d jeans, %d jars, and %d crates." % (beans,jars,crates))

start_point = start_point / 10

print("We can also do that this way: ")
print("We'd have %d beans, %d jars, and %d crabapples." % secret_formula(start_point))

sentence = "All good\tthings come to those who wait."

words = sentence.split()
sorted_words = sort_words(sentence)

print_first_word(sentence)
print_last_word(sentence)
print_first_word(sorted_words)
print_last_word(sorted_words)
sorted_words = sort_sentence(sentence)
print(sorted_words)

print_first_and_last(sentence)
print_first_and_last_sorted(sentence)

您在这里传递的是一个字符串:

sentence = "All good\tthings come to those who wait."
# ...
print_first_word(sentence)

你应该传递一个列表;大概您打算改为传入 words ;这是一个列表(str.split() 调用的结果):

words = sentence.split()

使用这个:

print_first_word(words)

而不是这个:

print_first_word(sentence)