A while loop might work well here:
def add_exclamation(word):
while len(word) < 20:
word += '!'
return word #, len(word) check
A while loop might work well here:
def add_exclamation(word):
while len(word) < 20:
word += '!'
return word #, len(word) check
Figured this might work as well:
Two more solutions:
The simplest would be:
return word.ljust(20,"!")
Using a for loop also works:
result = word
for i in range(20-len(word)):
result += "!"
return result
Instead of creating a new string every time, which happens when you use for or while loops, I generated a string of exclamations of length = 20-len(word), which is required for ‘word’ to reach 20 characters and added the string ‘word’ to the string of exclamations.
def add_exclamation(word):
if len(word) >= 20:
return word
word += ‘!’ * (20 - len(word))
return word
This is my code, I fill like i’m stupid )
def add_exclamation(word):
new = “”
new_string = 0
if len(word) <= 20:
new_string = 20 - len(word)
new = “!” * new_string
return word + new
return word
This is how I solved it:
def add_exclamation(word):
if len(word) < 20:
return word + "!"*(20 - len(word))
else:
return word
The line + "!"*(20 - len(word))
simply adds as many exclamation points as you require to reach 20 characters
Yeah this is even simpler than mine lol nice
This .ljust method is awesome. Where else can i find functions like this?
this is my solution:
def add_exclamation(word):
if len(word) >= 20:
return word
else:
x = 20 - len(word)
return word + ("!" * x)
Is slicing allowed?
>>> def add_exclamation(word):
return f"{word}{'!' * 20}"[:20]
>>> add_exclamation('')
'!!!!!!!!!!!!!!!!!!!!'
>>> add_exclamation('%' * 20)
'%%%%%%%%%%%%%%%%%%%%'
>>> add_exclamation('Hello World')
'Hello World!!!!!!!!!'
>>>
Excuse me I can not understand this.
Is there anything that you do understand about it?
I’ve noticed you have used the foramt method. How does [:20] do the trick?
That’s a string slice of the leftmost 20 characters.
def add_exclamation(word):
while len(word)<=19:
word= '!'.join([word, ''])
return(word)
# Uncomment these function calls to test your function:
print(add_exclamation("Codecademy"))
can you explain this method please ?
Sorry, but seems this will not return the word as it is, if it’s length more than 20 as they ask for…No?
" If word
is already at least 20
characters long, just return word
."
Ah, must have missed that instruction…
>>> def add_exclamation(word):
return word if len(word) > 20 else f"{word}{'!' * 20}"[:20]
>>> add_exclamation("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>>