-1

I seem to be creating lists within lists in this code. The .join at the end does work and removes the brackets, yet there are still more in the output. How do I fix this?

#method for encrypting message      
def encptMessage(keycol, msg):

   #adds the extra brackets and quotations
   #but don't know how to remove without
   #program failing
   ciphertxt = [''] *keycol
   
   #checkpoint 1
   print(ciphertxt)

   for column in range(keycol):
      pointer = column
  
      #increases row
      while pointer < len(msg):
         ciphertxt[column] += msg[pointer]
         #checkpoint 2
         print(ciphertxt)
         pointer += keycol
     
   return ''.join(ciphertxt)

#############################################################################

#runs if user wants to encrypt    
if (edchoice == "-e"):
   #applies key length and file text
   #to method
   ciphertxt = encptMessage(key, mytext)
   #outputs ciphertext

   #checkpoint 3
   print(ciphertxt + '|')
   print("Encryption is done")
   #sends ciphertext to a new file
   #or updates previous file
   fixedctxt = ciphertxt.replace('[','').replace(']','').replace("'",'')
   with open('encrypt.txt', 'w') as f:
      f.write(fixedctxt)
  • checkpoint 1: ['', '', '', '', '', '']
  • checkpoint 2: first loop: ['[', '', '', '', '', '']
  • checkpoint 2: 20th loop: ['[aaaa', "'aaaa", "aaaa'", 'aaaa]', '', '']
  • checkpoint 3: [ietg'ssmehiee'iscs]ttrshhea|
  • input: hithisisthesecretmessage
  • intended output: Ttrshheaietgssmeieescs|
philipxy
  • 14,867
  • 6
  • 39
  • 83
BFunk
  • 23
  • 5
  • 1
    What the input (`key`, `mytext`) for that output? – Klaus D. Feb 18 '22 at 05:01
  • It seems like what you want to do is `flatten` your array first. You do this when have an array that could contain inner arrays, but you are only concerned with the elements and want to consolidate all inner elements into a single list. For example, `[a , [b, c], [[d, e], f]]` -> [a, b, c, d, e, f]. Doing that then using a single join should work. Check out [this answer](https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-a-list-of-lists) on how to do it. – thekid77777 Feb 18 '22 at 05:29
  • I am not able to understand what you want to achieve, please explain in detail by editing your post. – Faraaz Kurawle Feb 19 '22 at 08:03

1 Answers1

0

I am not able to understand what you are trying to achieve, as your program successfully removes " [ "," ] ", and " ' ". It is also working as its intended to work.

Instead of executing fixedctxt = ciphertxt.replace('[','').replace(']','').replace("'",'') in the main program, you can just execute it in the encrytMessage function.

Here's what you can do:

  • Instead of returning .join string, you can join it and then execute fixedctxt = ciphertxt.replace('[','').replace(']','').replace("'",''), and then return fixedctxt.
Faraaz Kurawle
  • 1,085
  • 6
  • 24