Home > Mobile >  trying to decode @ into whitespace
trying to decode @ into whitespace

Time:03-27

origAlpha = string.ascii_lowercase   string.ascii_uppercase   string.digits    string.punctuation   ''

shift = int(input("what shift do you want to use to decode? "))
shiftAlpha = origAlpha[shift : ]   origAlpha[ : shift]
messageToDecode = 'k@nkmg@rtqitcookpi'
decodedMessage = ""
count = 0
while count < len(messageToDecode):
  nextLetter = messageToDecode[count]
  if(nextLetter=='@'):
      decodedMessage  = ' '
      
  elif nextLetter.isalpha():
      index = shiftAlpha.index(nextLetter)
      nextLetter = origAlpha[index]
  decodedMessage  = nextLetter
  count  = 1

im trying to decode the @ into whitespaces but its not working and cant seem to figure out the error can someone help- shift is 2 - i get this answer 'i@like@programming' when i want it 'i like pogramming'

CodePudding user response:

Note that you're including digits and punctuation in your origAlpha and shiftAlpha, even though you're checking for nextLetter.isalpha(), and digits and punctuation aren't alphabetic characters. That said, you unconditionally add nextLetter to decodedMessage. To make sure no @ characters get added, you can do something like this:

  nextLetter = messageToDecode[count]
  if nextLetter == '@':
      nextLetter = ' '
  elif nextLetter.isalpha():
      index = shiftAlpha.index(nextLetter)
      nextLetter = origAlpha[index]
  decodedMessage  = nextLetter

Bonus:

Instead of using origAlpha and shiftAlpha to find a string in linear time, consider using a dictionary, and instead of using a while loop, consider using a for loop. You can get something like this:

origAlpha = string.ascii_lowercase   string.ascii_uppercase   string.digits   string.punctuation

shift = int(input("what shift do you want to use to decode? "))
shiftAlpha = origAlpha[shift:]   origAlpha[:shift]

mapping_characters = dict(zip(shiftAlpha, origAlpha))
mapping_characters['@'] = ' '

message_to_decode = 'k@nkmg@rtqitcookpi'
decoded_message = ""
for letter in message_to_decode:
    decoded_message  = mapping_characters.get(letter, letter)

CodePudding user response:

I might be missing something but can you just use:

message = 'k@nkmg@rtqitcookpi'
decoded = message.replace('@', ' ')
  • Related