简体   繁体   English

python列表索引必须是整数而不是字符串

[英]python list indices must be integers not string

I'm trying to write a basic algorithm for encrypting a file. 我正在尝试编写一个加密文件的基本算法。 It takes the ASCII value of each character in a string and moves it up or down an amount depending on how long the password is, then you can layer more passwords on top. 它取字符串中每个字符的ASCII值,并根据密码的长度向上或向下移动一个数量,然后您可以在顶部添加更多密码。

def encrypt(s):
    lenStr=s.__len__() #used later for working how far the int is moved
    s=list(s) #converts the string to a list
    for x in s:
        s[x]=ord(s[x]) #the same index of the list is = to the value of the string
        s[x]=chr(s[x])#is where it eventualy gets changed back to a str

s=ord(s) is the line which is throwing the error, i added int() around it but didnt help, same error s=ord(s)是抛出错误的行,我在它周围添加了int()但没有帮助,同样的错误

x is a character from the string, not an integer. x是字符串中的字符,而不是整数。 Let me illustrate: 让我说明一下:

>>> s = list('abcd')
>>> for x in s:
...     print(x)
...
a
b
c
d
>>>

You want x to be integer values from 0 to the length of the string, like this: 您希望x是从0到字符串长度的整数值,如下所示:

>>> for x in range(len(s)):
...     print(x)
...
0
1
2
3
>>>

So, your function should probably look like this (untested): 所以,你的函数应该看起来像这样(未经测试):

def encrypt(s):
    lenStr=s.__len__() #used later for working how far the int is moved
    s=list(s) #converts the string to a list
    for x in range(len(s)):
        s[x]=ord(s[x]) #the same index of the list is = to the value of the string
        s[x]=chr(s[x])#is where it eventualy gets changed back to a str

I am guessing this is what you are aiming for: 我猜这是你的目标:

def encrypt(s):
    offset = len(s)
    return ''.join(chr(ord(c) + offset) for c in s)

def decrypt(s):
    offset = len(s)
    return ''.join(chr(ord(c) - offset) for c in s)

Some tips: 一些技巧:

  • Use len(s) instead of lenStr=s.__len__() 使用len(s)代替lenStr=s.__len__()
  • Naming values near their first use in the code improves readability. 在代码中首次使用它们附近的命名值可提高可读性。
  • Choose names that describe the use of the value. 选择描述值使用的名称。
  • Strings are iterable, same as lists. 字符串是可迭代的,与列表相同。 No need to convert a string into a list. 无需将字符串转换为列表。
  • Learn and use list comprehensions and generators whenever possible, they are usually much faster, simpler, easier to read and less error prone to create. 尽可能地学习和使用列表推导和生成器,它们通常更快,更简单,更易于阅读并且更不容易创建。
  • Remember to accept and/or upvote answers that are helpful. 请记住接受和/或提出有用的答案。

You're getting the TypeError exception because the value of x in the s[x]=ord(s[x]) statement is one of the elements of the s list, so it's an individual character from the string argument passed to encrypt() . 你得到TypeError异常,因为值xs[x]=ord(s[x])语句是的要素之一s名单,所以它是从传递给字符串参数的个性encrypt() To fix that, just loop through all the possible indices of the s list which happens to be the same as the length as the original string: 要解决这个问题,只需遍历s列表中所有可能的索引,这些索引恰好与原始字符串的长度相同:

def encrypt(s):
    lenStr=len(s)
    s=list(s) # convert the string to a list
    for i in range(lenStr):
        s[i]=ord(s[i])
        s[i]=chr(s[i])

This will allow your code to run without getting that error. 这将允许您的代码运行而不会出现该错误。 From your description of the encryption algorithm you're going to implement, one thing to watch out for is producing illegal 8-bit character values out of the range of 0-255. 根据您要实现的加密算法的描述,需要注意的一件事是生成0-255范围之外的非法8位字符值。 You can avoid that problem by simply applying the mod operator % to the intermediate results to keep the values in the proper range. 您可以通过简单地将mod运算符%应用于中间结果来避免该问题,从而将值保持在适当的范围内。 Here's what I mean: 这就是我的意思:

def encrypt(s):
    lenStr = len(s)
    s = list(s) # convert the string to a list
    for i in range(lenStr):
        s[i] = chr((ord(s[i]) + lenStr) % 256)
    return ''.join(s) # convert list back into a string

Likewise, you'll have to do the same thing when you decrypt a string: 同样,在解密字符串时,您必须执行相同的操作:

def decrypt(s):
    lenStr = len(s)
    s = list(s) # convert the string to a list
    for i in range(lenStr):
        s[i] = chr((ord(s[i]) - lenStr) % 256)
    return ''.join(s) # convert list back into a string

enc = encrypt('Gnomorian')
print('encrypted:', enc)
dec = decrypt(enc)
print('decrypted:', dec)

Output: 输出:

encrypted: Pwxvx{rjw
decrypted: Gnomorian

Also note that not all the characters whose ord() values are in the range of 0-255 are printable, so you may want to restrict the encryption transformation even more if that's a requirement (that the encrypted version be printable). 另请注意,并非所有ord()值都在0-255范围内的字符都是可打印的,因此如果需要(加密版本可打印),您可能需要更加限制加密转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM