我正在尝试编写一个简短的脚本,将单词或句子转换为其字母值,然后向前跳转 5 个值,并将结果打印为字符串。 例如
['a', 'b', 'c']
应该改为...
'102 103 104'
但是,我只得到上面的错误。 有问题的代码:
def enc(input, output, seq, str_int):
input = input.lower()
output = []
for char in input:
num = ord(char) + 5
str_int = str(num)
output.append(str_int)
output = seq.join(output)
return output
print(enc("hello", [], ' ', ' '))
我确定我只是遗漏了一些非常明显的东西。谢谢。
请您参考如下方法:
出现问题是因为线路-
output = seq.join(output)
根据缩进,这是在 for 循环内,因此在 for 循环内,您正在将 output 变量更改为 str (string) ,之后当您尝试执行 output.append() 时,它会出错。这是问题的主要原因。
我猜您实际上只是打算在完全创建 output 列表之后在循环之外执行此操作。但你真的不需要将其设置回去,你可以简单地做 -
def enc(input, output, seq, str_int):
input = input.lower()
for char in input:
num = ord(char) + 5
str_int = str(num)
output.append(str_int)
return seq.join(output)
演示 -
>>> def enc(input, output, seq, str_int):
... input = input.lower()
... for char in input:
... num = ord(char) + 5
... str_int = str(num)
... output.append(str_int)
... return seq.join(output)
...
>>> print(enc("hello", [], ' ', ' '))
109 106 113 113 116
