简体   繁体   English

我如何使这个程序与空格一起工作? (文本到 ASCII 和 ASCII 到文本)

[英]How do I make this program work with spaces? (Text to ASCII and ASCII to text)

I wrote a program that turns a text into ASCII numbers, and then it turns the ASCII numbers back into the original text.我编写了一个程序,将文本转换为 ASCII 数字,然后将 ASCII 数字转换回原始文本。 Right now it works with both lowercase letters and uppercase letters but it doesn't work with spaces.现在它适用于小写字母和大写字母,但不适用于空格。 This is how my code looks right now:这是我的代码现在的样子:

message_hidden = input("Enter a message that will be hidden: ")
hidden = ""
norm_message = ""
for i in message_hidden:
    hidden = hidden + str(ord(i)-23)
print(hidden)

for i in range(0, len(hidden), 2):
    code = hidden[i] + hidden[i+1]
    norm_message = norm_message + (chr(int(code)+23))
print("The first message was: ", norm_message)

My first attempt was to rewrite the first loop like this:我的第一次尝试是像这样重写第一个循环:

for i in message_hidden:
    if i.isalpha():
        hidden = hidden + str(ord(i)-23)
    else:
        hidden = hidden + i
print(hidden)

And from here I don't know how I should write the second loop to make it work.从这里我不知道我应该如何编写第二个循环以使其工作。 Can anyone give me some suggestions about how I should go from here?谁能给我一些关于我应该如何从这里开始的建议?

ord(' ') == 32 and 32-23 == 9 , which is single digit. ord(' ') == 32 and 32-23 == 9 ,这是个位数。 You are assuming that your numerical codes are all 2 digits.您假设您的数字代码都是 2 位数字。 If you want to keep that assumption, you need to find a different way to encrypt the space character.如果你想保持这个假设,你需要找到一种不同的方法来加密空格字符。 To do this find a 2-digit number that isn't one of the numbers obtained by a-zA-Z .为此,请找到一个不是a-zA-Z获得的数字之一的 2 位数字。 Using an explicit if -- encrypt the space character to this number.使用显式if -- 将空格字符加密为此数字。 When decrypting, you will also need to use an explicit if to handle this case.解密时,您还需要使用显式if来处理这种情况。

Alternatively, find a different function (other that subtracting by 23), which you apply to ord(letter) -- one which gives 2 digit numbers for all ord() values that you are interested in. There are infinitely many functions which satisfy this property.或者,找到一个不同的函数(除 23 之外的其他函数),将其应用于ord(letter) - 一个为您感兴趣的所有ord()值提供 2 位数字的函数。有无数个函数可以满足这一点财产。 Whether or not you can find one which would require less code than simply putting a band aid on the space character is another question.您是否可以找到一个比简单地在空格字符上放置创可贴需要更少代码的代码是另一个问题。

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

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