Python “str”对象没有属性“len”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41368066/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 00:52:03  来源:igfitidea点击:

'str' object has no attribute 'len'

pythondjangoloopsscope

提问by user1778743

Ive got a method that use to work by checking the first three letters/numbers and making sure they are the same before it continues like so

我有一种方法可以通过检查前三个字母/数字并确保它们在继续之前相同来工作

def combineProcess(request):
    carID1 = request.POST['carID1']
    carID2 = request.POST['carID2']
    for x in range (0,3):
        a += carID1.length(x)
        b += carID2.length(x)
    if a.equals(b):
        //do something

before it use to work now it stopped and i get this error.

在它用于工作之前,它停止了,我收到了这个错误。

Exception Type: UnboundLocalError
Exception Value:    

local variable 'a' referenced before assignment

which i never use to get a few weeks ago didnt change anything so i made a and b global.

几周前我从未使用过它并没有改变任何东西,所以我将 a 和 b 设为全局。

def combineProcess(request):
    carID1 = request.POST['carID1']
    carID2 = request.POST['carID2']
    global a,b
    for x in range (0,3):
        a += carID1.length(x)
        b += carID2.length(x)
    if a.equals(b):
        //do something

Now I am getting this error.

现在我收到此错误。

Exception Type: NameError
Exception Value:    

name 'a' is not defined

Then i removed the global line and just put this

然后我删除了全局行并把这个

a = "P"

and got the following error

并得到以下错误

str object has no attribute length() or len()

which now has me puzzled how has this code stop working and why cant it recognize that a string object has a len() method. mainly I am lost how my code went from working to not working over a two weeks off.

现在让我感到困惑的是这段代码如何停止工作以及为什么它不能识别字符串对象具有 len() 方法。主要是我迷失了我的代码是如何在两周内从工作变为不工作的。

回答by Wasi Ahmad

Python String len() Method

Python 字符串 len() 方法

Syntax

句法

Following is the syntax for len() method ?

以下是 len() 方法的语法?

len( str )

Example

例子

str = "this is string example....wow!!!";
print("Length of the string: ", len(str))

When we run above program, it produces following result ?

当我们运行上面的程序时,它会产生以下结果?

Length of the string:  32

Reference: Python String len() Method

参考Python String len() 方法

UnboundLocalError: local variable 'a' referenced before assignment

UnboundLocalError:赋值前引用了局部变量“a”

Explanation

解释

This is because, even though aand bexists, you're also using an assignment statement on the name aand binside of the function combineProcess(). Naturally, this creates a variable inside the function's scope called aand b.

这是因为,即使存在a并且b存在,您也在函数名称ab内部使用赋值语句combineProcess()。自然地,这会在函数的作用域内创建一个名为aand的变量b

The Python interpreter sees this at module load time and decides that the global scope's of aand bshould not be used inside the local scope, which leads to a problem when you try to reference the variable before it is locally assigned.

Python 解释器在模块加载时看到这一点,并决定全局范围的ab不应在局部范围内使用,这会导致在本地分配变量之前尝试引用变量时出现问题。

Example

例子

Var1 = 1
Var2 = 0
def function():
    if Var2 == 0 and Var1 > 0:
        print("Result One")
    Var1 =- 1

function()

If you run this program, it gives the following error.

如果您运行此程序,则会出现以下错误。

UnboundLocalError: local variable 'Var1' referenced before assignment

Since, the value of Var1is modified, this creates a variable inside the function's scope called Var1. As a result error is reported because of the condition check, Var1 > 0before the Var1 =- 1statement.

由于Var1修改了 的值,这会在函数的作用域内创建一个名为 的变量Var1。结果,Var1 > 0Var1 =- 1语句之前,由于条件检查而报告错误。

But if we modify the code as follows.

但是如果我们修改代码如下。

Var1 = 1
Var2 = 0
def function():
    global Var1
    if Var2 == 0 and Var1 > 0:
        print("Result One")
    Var1 =- 1

function()

Then it works fine.

然后它工作正常。

Note that, if we move the statement Var1 =- 1before the ifcondition check, then it will not report any error even if you don't use global Var1statement. So, the following code works fine.

请注意,如果我们Var1 =- 1if条件检查之前移动语句,那么即使您不使用global Var1语句,它也不会报告任何错误。所以,下面的代码工作正常。

Var1 = 1
Var2 = 0
def function():
    Var1 =- 1
    if Var2 == 0 and Var1 > 0:
        print("Result One")

function()

Reference: See this SO answer.

参考:请参阅此 SO答案

NameError: name 'a' is not defined

NameError: 名称 'a' 未定义

Explanation

解释

Probably you are getting this error because in Python, you cannot compare two strings using equals()method. There is no such method exists.

您可能会收到此错误,因为在 Python 中,您无法使用equals()方法比较两个字符串。不存在这样的方法。

Example: Comparing two strings

示例:比较两个字符串

You can use > , < , <= , <= , == , !=to compare two strings. Python compares string lexicographically i.e using ASCII value of the characters. For example, to compare two strings for equality, you can do as follows.

您可以使用> , < , <= , <= , == , !=来比较两个字符串。Python 按字典顺序比较字符串,即使用字符的 ASCII 值。例如,要比较两个字符串是否相等,您可以执行以下操作。

if string1 == string2:
    // do something

回答by FlipTack

I assume you've come from a language such as Java where you call functions directly on strings. You coulddo that in Python:

我假设您来自 Java 之类的语言,您可以直接在字符串上调用函数。你可以在 Python 中做到这一点:

>>> A = "Hello"
>>> B = "Hello"
>>> A.__len__()
5

>>> A.__eq__(B)
True

However, the proper way of doing it is like so:

但是,正确的做法是这样的:

>>> len(A)
5

>>> A == B
True


With that being said, I'm not sure what you're trying to accomplish with the length function there. You said your code is checking whether the first 3 letters of the 2 strings are the same - you can do that like so:

话虽如此,我不确定你想用那里的长度函数来完成什么。您说您的代码正在检查 2 个字符串的前 3 个字母是否相同 - 您可以这样做:

A = "car123"
B = "car456"

print(A[:3] == B[:3]) # -> True

This uses Python's slice notation to get the first 3 characters of each string, and compares these slices with each other.

这使用 Python 的切片符号来获取每个字符串的前 3 个字符,并将这些切片相互比较。