如何从字符串中取出值?Python

2024-04-27 19:23:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我的任务是创建一个偏移因子,它基于程序前面计算的8个字符的键。首先,需要将8个字符密钥中的每个字符转换为等效的ascii数字,然后相加,然后将结果除以8,然后向下舍入为整数。最后,需要从该值中减去32。在

这是我在偏移因子之前的代码:

def EncryptCode():
    userFileLoad = input("Name the file and directory you want to load with the ending '.txt':\n")
    with open (userFileLoad,mode="r",encoding="utf=8") as encrypt_file:
        encrypt = encrypt_file.read()
    print ("Code that will be encrypted:")
    printMessage(encrypt)
    eightNumKey = (chr(random.randint(33,126)) for _ in range(8))
    print('\nEight-Character Key:', "".join(eightNumKey))

这就是我试图在程序中实现偏移因子的方法:

^{pr2}$

我的输出显示:

This program has three choices.

1. Encrypt a message.

2. Decrypt the message.

3. Exit the program.


Make your choice: 1
Name the file and directory you want to load with the ending '.txt':
Sample.txt
Code that will be encrypted:


Somewhere in la Mancha, in a place whose name I do not care to remember, a gentleman lived not long ago, one of those who has a lance and ancient shield on a shelf and keeps a skinny nag and a greyhound for racing.

Eight-Character Key: txJ#K_P`
Traceback (most recent call last):
  File "N:\Computer Science\Course Work\Controlled assessment\Controlled Assessment.py", line 54, in <module>
showMenu()
  File "N:\Computer Science\Course Work\Controlled assessment\Controlled Assessment.py", line 38, in showMenu
    EncryptCode()
  File "N:\Computer Science\Course Work\Controlled assessment\Controlled Assessment.py", line 26, in EncryptCode
    offsetFactor = offsetFactor + ord(eightNumKey)
TypeError: ord() expected string of length 1, but generator found

Tags: andthetointxtwithcomputer因子
3条回答

@JaimeCockburn有你问题的答案。我想展示如何使用xrangerandom.sample重构代码,避免将数字转换成字符串,然后再转换回数字。在

>>> 
>>> ints = xrange(33, 127)
>>> key = random.sample(ints, 8)
>>> key
[78, 75, 77, 73, 94, 60, 44, 67]
>>> offset = sum(key)
>>> offset
568
>>> key = ''.join(map(chr, key))
>>> key
'NKMI^<,C'

ints可以重用。在

^{pr2}$

想试试这个:

offset_factor = 0
    for i in range(0, 8):
        offset_factor = offset_factor + ord(key[i])
    offset_factor = offset_factor // 8 - 32

在这条线上:

eightNumKey = (chr(random.randint(33,126)) for _ in range(8))

(a for x in y)语法创建一个生成器。生成器是一种可以迭代的东西,但它会在迭代过程中创建每一项。实际的项不是在该点创建的,而是在它们被访问时创建的。在

然后,当打印出生成器中的所有项时,可以迭代这些项:

^{pr2}$

在这一行之后,生成器是空的,您再也不能取回这些项目了。在

最后,您试图得到生成器的序数值,这没有任何意义:

offsetFactor = offsetFactor + ord(eightNumKey)  # eightNumKey is a generator

解决方案

你真的想要这样的东西:

# Create a list, not a generator
eightNumKey = [chr(random.randint(33, 126)) for _ in range(8)]
# Iterate the list to print them out
print('\nEight-Character Key:', "".join(eightNumKey))
# Iterate the list again to sum the ordinal values
offsetFactor = sum(ord(c) for c in eightNumKey)
...

更新: 正如一位评论者提到的,您实际上在做ord(chr(random_number)),这有点多余,因为最终结果又是random_number。您只需将整数值存储在列表中,并在打印时将其转换为字符,省去了来回转换的麻烦。在

相关问题 更多 >