Reputation: 11
I am trying to create a python code which will encrypt and decrypt words and everything works except the block encryption. I just need to find a way to get rid of all of the spaces - here is the code I've been using
#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
This is my code. At the bit where it says:
if mode[0] == 'be':
string.replace(" ","")
This is my attempt at getting rid of the spaces which does not work. If anyone could help, that would be good. Making it one space every 5 letters would be even better, but I don't need that. Thank you for your help
Upvotes: 1
Views: 847
Reputation: 1
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
Upvotes: 0
Reputation: 25329
Python strings are immutable.
Therefore string.replace(" ","")
doesn't modify string
, but returns a copy of string
without spaces. The copy is discarded later, because you do not associate a name with it.
Use
string = string.replace(" ","")
Upvotes: 3