AttributeError: 'str' object has no attribute 'pop' 什么意思求解答

def print_first_word(words):
    """Prints the first word after popping it off."""

    print ( words.pop(0))
sentence = "All god\tthings come to those who weight."

print_first_word(sentence)

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

阅读 6.7k
2 个回答
def print_first_word(words):
    """Prints the first word after popping it off."""
    # 三种方法都可以
    print ( words[0] )
    print ( list(words).pop(0) )
    print ( list(words)[0] )
sentence = "All god\tthings come to those who weight."

print_first_word(sentence)

提示内容翻译一下就知道了:

'str' 类型的对象没有 'pop' 这个属性

函数本身的设计上应该是要传入列表,但是你传入的 sentence 明显是一个字符串,你可以修改函数使它可以处理字符串,也可以修改传入的参数把它变成列表。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏