Python AttributeError:' str'对象没有属性' pop' Learnpythonthehardway

时间:2016-10-23 10:31:43

标签: python string attributes attributeerror pop

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

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

以下是回溯错误:Traceback(最近一次调用最后一次):

  

文件" C:\ Python34 \ ex26.py",第74行,in       print_first_word(句子)文件" C:\ Python34 \ ex26.py",第10行,在print_first_word中       word = words.pop(0)

     

属性错误:' str'对象没有属性' 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)

2 个答案:

答案 0 :(得分:0)

你在这里传递一个字符串:

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

你打算传入一个清单;大概是你打算通过words来代替;这是一个列表(str.split()调用的结果):

words = sentence.split()

答案 1 :(得分:0)

使用此:

print_first_word(words)

而不是:

print_first_word(sentence)