Error message with StringReplace "Not a valid string replacement rule"

Following an example from my lectures, I get this error and can't explain why it occurs.

The instructions are as follows:

alphabet = CharacterRange("A","Z");
string = "THIS IS THE TEXT TO ENCRYPT"
rc = RandomColor(26)
code = Table(alphabet((n))->rc((n)),{n,Length(alphabet)})
newstring = StringReplace(string, code)

but sometimes (but not always) I get this error: "StringReplace :: srep: Z -> () is not a valid string replacement rule" where () represents a certain color.

Could you help me understand why it happens?