1

I need some help removing the extra space before a word/string ends. Does anyone have any ideas?

input:

hello

output I get (two spaces at the end):

' ....  .  .-..  .-..  ---  '

expected output (only one space at the end, but two spaces between letters):

' ....  .  .-..  .-..  --- '

Here's my code:

MORSE_CODES={'A':'.-','B':'-...','C':'-.-.',
'D':'-..','E':'.','F':'..-.','G':'--.',
'H':'....','I':'..','J':'.---','K':'-.-',
'L':'.-..','M':'--','N':'-.','O':'---',
'P':'.--.','Q':'--.-','R':'.-.',
'S':'...','T':'-','U':'..-','V':'...-',
'W':'.--','X':'-..-','Y':'-.--','Z':'--..'}


def encode_Morse(my_msg):
  my_msg=my_msg.upper()

  my_msg_Morse=" "
  for letter in my_msg:
    
    if letter!=" " and letter not in MORSE_CODES:
      my_msg_Morse+=" * "
    elif letter!=" ":
       my_msg_Morse+= MORSE_CODES[letter]+"  "
    else:
      my_msg_Morse+=" "

  return my_msg_Morse
Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
qwvst
  • 51
  • 5

3 Answers3

2

You could just do:

my_msg_Morse_list.replace(' ','')

Edited

I was corrected, If the problem is always two spaces at the maybe you could just trim the string with

my_msg_Morse = my_msg_Morse[:-1]
0

I would use the split() method on your string to parse out your morse code into an iterable and then iterate over each code, first using strip() and then ignoring empty elements.

Keiron Stoddart
  • 328
  • 3
  • 12
0

You can do this one of two ways:

  1. Keep track of the index of every letter in your iteration using enumerate(). Check if this is the last letter in my_msg. If it is, don't add the second space.
def encode_Morse(my_msg):
  my_msg=my_msg.upper()

  my_msg_Morse=" "
  for index, letter in enumerate(my_msg):
    
    if letter!=" " and letter not in MORSE_CODES:
      my_msg_Morse+=" * "
    elif letter!=" ":
       my_msg_Morse+= MORSE_CODES[letter] + " "
       if index < len(my_msg) - 1:
           my_msg_Morse += " "
    else:
      my_msg_Morse+=" "

  return my_msg_Morse
  1. Build a list and then use str.join() to join it with spaces. We'll also have to add one space before and after the result of the join().
def encode_Morse(my_msg):
  my_msg=my_msg.upper()

  my_msg_Morse_list = []
  for letter in my_msg:
    if letter=" " and letter not in MORSE_CODES:
      my_msg_Morse_list.append("*")
    elif letter!=" ":
       my_msg_Morse_list.append(MORSE_CODES[letter])
    else:
      my_msg_Morse_list.append(" ")
  # Add the leading and trailing space
  return " " + "  ".join(my_msg_Morse_list) + " "

I'm going to rewrite your function to make the if-else ladder a little more clear. First, I'm going to add a value for a space in the MORSE_CODES dictionary. This eliminates the need to check if letter is a space. Then, I'm going to use the dict.get() function to get the value of the key letter from MORSE_CODES. get() lets us specify a default value to be returned if the given key doesn't exist in the dictionary.


MORSE_CODES={'A':'.-','B':'-...','C':'-.-.',
'D':'-..','E':'.','F':'..-.','G':'--.',
'H':'....','I':'..','J':'.---','K':'-.-',
'L':'.-..','M':'--','N':'-.','O':'---',
'P':'.--.','Q':'--.-','R':'.-.',
'S':'...','T':'-','U':'..-','V':'...-',
'W':'.--','X':'-..-','Y':'-.--','Z':'--..', ' ': ' '}

def encode_Morse(my_msg):
  my_msg=my_msg.upper()
  my_msg_Morse_list = []
  for letter in my_msg:
    morse_letter = MORSE_CODES.get(letter, "*")
    my_msg_Morse_list.append(morse_letter)

  # Add the leading and trailing space
  return " " + "  ".join(my_msg_Morse_list) + " "

When you do all these things, you can write your entire function in one line if you'd like using a generator expression in place of the loop:

def encode_Morse(my_msg):
  return " " + "  ".join(MORSE_CODES.get(letter, "*") for letter in my_msg.upper()) + " "

For every function, you can check that it gives the expected output by checking that the following code gives True

' ....  .  .-..  .-..  --- ' == encode_Morse("hello")
Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
  • why would I have to create a list ? – qwvst Apr 14 '21 at 17:56
  • So that you can use `str.join()` to join all elements of the list with two spaces between them `" ".join(["a", "b"])` gives you `"a b"` – Pranav Hosangadi Apr 14 '21 at 17:57
  • can you add another elif statement that could say not to put a space after the last letter in a string? – qwvst Apr 14 '21 at 18:23
  • Your question says you want _one_ space after the last letter. What do you actually want? – Pranav Hosangadi Apr 14 '21 at 18:24
  • I need two spaces between morse letters and one space after the last morse character. – qwvst Apr 14 '21 at 18:26
  • That is what all the functions I have given you do. What do you want to _"add another elif statement that could say not to put a space after the last letter in a string"_ for? And which function are you referring to when you say that? – Pranav Hosangadi Apr 14 '21 at 18:28
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/231140/discussion-between-pranav-hosangadi-and-qwvst). – Pranav Hosangadi Apr 14 '21 at 18:29