如何摆脱python中凯撒转换程序的空间?

时间:2015-05-14 11:32:18

标签: python encryption caesar-cipher

我正在尝试创建一个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个字母创建一个空格会更好,但我不需要。 谢谢你的帮助

2 个答案:

答案 0 :(得分:2)

Python字符串是immutable

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

使用

string = string.replace(" ","")

答案 1 :(得分: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