首页 > 解决方案 > 如何修复返回 TypeError 的 len() 命令?

问题描述

我正在尝试在 python 中计算字符串的长度,但是我似乎无法得到正确的响应。如果有人能告诉我我做错了什么,我将不胜感激。代码:

name = input("Type a string!")
name = name.upper
lenname = len(name)
if lenname == 3:
    print("Success")
else:
    print("Fail")

我希望输出是Success当我输入abc但我收到:

TypeError                                 Traceback (most recent 
call last)
<ipython-input-20-1de45569cf05> in <module>
      1 name = input("Type a string!")
      2 name = name.upper
----> 3 lenname = len(name)
      4 if lenname == 3:
      5     print("Sucess")

TypeError: object of type 'builtin_function_or_method' has no len()

标签: python

解决方案


您正在尝试upper像访问字段而不是方法一样访问。在上面你使用的那一行len,做name = name.upper()


推荐阅读