1

我正在尝试创建一个 python 代码,它将加密和解密单词,除了块加密之外一切正常。我只需要找到一种方法来摆脱所有的空间 - 这是我一直在使用的代码

    #Stops the program going over the 25 (because 26 would be useless)
#character limit
MAX = 25

#Main menu and ensuring only the 3 options are chosen
def getMode():
    while True:
        print('Main Menu: Encrypt (e), Decrypt (d), Stop (s), Block Encrypt (be).')
        mode = input().lower()
        if mode in 'encrypt e decrypt d block encrypt be'.split():
            return mode
        if mode in 'stop s'.split():
            exit()
        else:
            print('Please enter only "encrypt", "e", "decrypt", "d", "stop", "s" or "block encrypt", "be"')

def getMessage():
    print('Enter your message:')
    return input()

#Creating the offset factor 
def getKey():
    key = 0
    while True:
        print('Enter the offset factor (1-%s)' % (MAX))
        key = int(input())
        if (key >= 1 and key <= MAX):
            return key

#Decryption with the offset factor       
def getTranslatedMessage(mode, message, key):
    if mode[0] == 'd':
#The key is inversed so that it simply takes away the offset factor instead
#of adding it        
        key = -key
    translated = ''

    if mode[0] == 'be':
        string.replace(" ","")

        #The spaces are all removed for the block encryption

#Ensuring that only letters are attempted to be coded
    for symbol in message:
        if symbol.isalpha():
            number = ord(symbol)
            number += key
#Ensuring the alphabet loops back over to "a" if it goes past "z"
            if symbol.isupper():
                if number > ord('Z'):
                    number -= 26
                elif number < ord('A'):
                    number += 26
            elif symbol.islower():
                if number > ord('z'):
                    number -= 26
                elif number < ord('a'):
                    number += 26

            translated += chr(number)
        else:
            translated += symbol
    return translated
#Returns translated text

mode = getMode()
message = getMessage()
key = getKey()
#Retrieving the mode, message and key

print('The translated message is:')
print(getTranslatedMessage(mode, message, key))
#Tells the user what the message is

这是我的代码。在它说的地方:

if mode[0] == 'be': 
    string.replace(" ","")

这是我试图摆脱无效空间的尝试。如果有人可以提供帮助,那就太好了。每 5 个字母设置一个空格会更好,但我不需要。谢谢您的帮助

4

2 回答 2

3

Python 字符串是不可变的。

因此string.replace(" ","")不修改,而是返回不带空格string的副本。string该副本稍后会被丢弃,因为您没有将名称与其关联。

利用

string = string.replace(" ","")
于 2015-05-14T12:42:08.433 回答
0
import re

myString = "I want to Remove all white \t spaces, new lines \n and tabs \t"

myString = re.sub(r"[\n\t\s]*", "", myString)

print myString
于 2019-09-03T23:03:47.813 回答