Search code examples
pythonstringlistattributesattributeerror

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


I have this on-going problem with this error which I tried to solve as the tutorial has told me fix this code. Most of the code is spelling and math errors, however I cannot solve this AttributeError.

Tutorial site: https://learnpythonthehardway.org/book/exercise26.txt

Here is the traceback error: Traceback (most recent call last):

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'

My code which i had to fix the tutorial code as a test:

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)

Solution

  • You are passing in a string here:

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

    You are meant to pass in a list; presumably you meant to pass in words instead; that's a list (the result of the str.split() call):

    words = sentence.split()