2013-07-19 41 views
1

我正在尝试编写一个加密文件的基本算法。它取一个字符串中每个字符的ASCII值,并根据密码的长度将其上下移动一个数量,然后您可以在顶部添加更多的密码。python list indices必须是整数而不是字符串

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)是被投掷错误的行,我添加INT()围绕它,但没有帮助,相同的错误

回答

1

你得到TypeError例外,因为xs[x]=ord(s[x])语句中的值是s列表的元素之一,所以这是从传递给encrypt()字符串参数的个性。为了解决这个问题,只是遍历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]) 

这将使你的代码没有得到该错误运行。根据您要实现的加密算法的描述,需要注意的一件事是在0-255范围内生成非法的8位字符值。只需将mod运算符%应用于中间结果以将值保持在适当的范围内即可避免该问题。这就是我的意思是:

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 

同样,你必须做同样的事情,当你解密的字符串:

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) 

输出:

encrypted: Pwxvx{rjw 
decrypted: Gnomorian 

另外请注意,并非所有的ord()值在0-255范围内的字符是可打印的,所以如果这是一个要求(即加密版本是printabl),您可能希望更加限制加密转换E)。

+0

谢谢,你也解决了我以后用%256碰到的问题,也许即时格式化它错了,但是当我输入文件中的行:print(lines)even tho there是只有一行与“你好世界”,这就是我想加密它打印它的空间两次,当我用它上面的固定代码加密打印:你好世界 SZwazd}澳@martineau – Gnomorian

+0

很难说什么可能导致这样的双重打印...也许你没有返回你的版本中的加密值。无论如何,如果你认为我的答案是值得的,请考虑对它进行投票。谢谢。 – martineau

+0

我还没有声望做到这一点,但当我生病回来这样做 – Gnomorian

1

x是从字符串的字符,而不是一个整数。让我来举例说明:

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

你想X是整数值从0到字符串的长度,这样的:

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

所以,你的功能也许应该是这样的(未经测试):

 
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 
+0

谢谢!工作 – Gnomorian

+0

@Gnomorian:你为什么不接受这个答案? – refi64

+0

不知道如何,没有看到按钮这样做 – Gnomorian

1

我猜这就是你的目标为:

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) 

一些提示:

  • 使用lenStr=s.__len__()len(s)代替
  • 命名在附近的代码在第一次使用值提高了可读性。
  • 选择描述值使用的名称。
  • 字符串可迭代,与列表相同。无需将字符串转换为列表。
  • 尽可能学习和使用列表推导和生成器,它们通常更快,更简单,更易于阅读并且不易出错。
  • 请记住接受和/或上传有用的答案。
相关问题