Sharing Solutions

There’s probably a better way to repeat than re-running the whole function, but it works.

def add_exclamation(word):

while len(word)<20:

word+='!'

return word

def add_exclamation(word):
  while len(word) < 20:
    word += '!'
  return word

I used the same code as a lot of other people, but I’m curious as to why .append() doesn’t work in this situation and why += is used instead? Because the paramater word is a string, shouldn’t we be using .append()? I know the answer is no because it didn’t work, but I would like to know why for the future.

Anyway, here was my final result after finding .append() didn’t work:

def add_exclamation(word):
  while len(word) < 20:
    word += "!"
  return word

.append() is used solely for lists. Since word is a string, we can’t use .append(). This makes a lot of sense when you think about how strings are immutable (meaning they can’t be changed. While .append() would modify object, word += "!" would not since it is essentially word = word + "!". Using +=, you are reassigning the value of word which is valid (modifying word would be invalid since strings are immutable).

Here is my solution:

def add_exclamation(word):
  return f'{word:!<20s}'

its as simple as I could make it. Apparently multiplying a string by -ints doesnt cause issues. i guess thats pretty cool

def add_exclamation(word):
return word + (’!’ * (20 - len(word)))