You can do this one of two ways:
- 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
- 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")