【问题标题】:Python error: AttributeError: 'str' object has no attribute 'pop'Python 错误:AttributeError:“str”对象没有属性“pop”
【发布时间】:2017-06-02 05:35:45
【问题描述】:

这是我遇到问题的代码:

def break_words(stuff):
"""This function will break up words."""
words = stuff.split(' ')
return words

def sort_words(words):
"""Sorts the words."""
return sorted(words)
def print_first_word(words):

def print_first_word(words):
"""Prints the first word after popping it off."""
word = raw_input('> ')
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

当我在终端中调用脚本时,我得到了

Traceback (most recent call last):
  File "ex.py", line 87, in <module>
    print_first_word(words)
  File "ex.py", line 15, in print_first_word
    word = words.pop(0)
AttributeError: 'str' object has no attribute 'pop'

我不明白这一点,因为在不同的文件中,我的代码基本相同,并且我在与此处完全相同的上下文中使用 pop。 (这是 Learn Python The Hard Way 练习 26 中的一个练习)

【问题讨论】:

    标签: python python-2.7 list


    【解决方案1】:

    一切都是正确的,因为字符串没有 pop 方法,但是您可以将 print_first_word 转换为列表。

    【讨论】:

      猜你喜欢
      • 2023-03-05
      • 2020-09-28
      • 1970-01-01
      • 2018-03-15
      • 1970-01-01
      • 1970-01-01
      • 2018-12-01
      • 2015-09-30
      • 2021-10-22
      相关资源
      最近更新 更多