[python] SyntaxError: cannot assign to operator

def RandomString (length,distribution):
    string = ""
    for t in distribution:
        ((t[1])/length) * t[1] += string
    return shuffle (string)

This returns a syntax error as described in the title. In this example, distribution is a list of tuples, with each tuple containing a letter, and its distribution, with all the distributions from the list adding up to 100, for example:

[("a",50),("b",20),("c",30)] 

And length is the length of the string that you want.

This question is related to python syntax-error

The answer is


What do you think this is supposed to be: ((t[1])/length) * t[1] += string

Python can't parse this, it's a syntax error.


Instead of ((t[1])/length) * t[1] += string, you should use string += ((t[1])/length) * t[1]. (The other syntax issue - int is not iterable - will be your exercise to figure out.)


Well, as the error says, you have an expression (((t[1])/length) * t[1]) on the left side of the assignment, rather than a variable name. You have that expression, and then you tell Python to add string to it (which is always "") and assign it to... where? ((t[1])/length) * t[1] isn't a variable name, so you can't store the result into it.

Did you mean string += ((t[1])/length) * t[1]? That would make more sense. Of course, you're still trying to add a number to a string, or multiply by a string... one of those t[1]s should probably be a t[0].


in python only work

a=4
b=3

i=a+b

which i is new operator


In case it helps someone, if your variables have hyphens in them, you may see this error since hyphens are not allowed in variable names in Python and are used as subtraction operators.

Example:

my-variable = 5   # would result in 'SyntaxError: can't assign to operator'