簡體   English   中英

如何擺脫python中凱撒轉換程序的空間?

[英]How do I get rid of the spaces for my Caesar shift program in python?

我正在嘗試創建一個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個字母創建一個空格會更好,但我不需要。 謝謝您的幫助

Python字符串是不可變的

因此, string.replace(" ","")不會修改string ,但會返回不帶空格的string副本。 稍后會丟棄該副本,因為您沒有將名稱與其關聯。

采用

string = string.replace(" ","")
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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM