# Sharing Solutions

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:

8 Likes

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
``````
5 Likes

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.

if len(word) >= 20:
return word

word += ‘!’ * (20 - len(word))
return word

5 Likes

This is my code, I fill like i’m stupid )

new = “”
new_string = 0
if len(word) <= 20:
new_string = 20 - len(word)
new = “!” * new_string
return word + new
return word

1 Like

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

4 Likes

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]

'!!!!!!!!!!!!!!!!!!!!'
'%%%%%%%%%%%%%%%%%%%%'
'Hello World!!!!!!!!!'
>>>
``````
2 Likes

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:
``````
1 Like

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` ."

1 Like

Ah, must have missed that instruction…

``````>>> def add_exclamation(word):
return word if len(word) > 20 else f"{word}{'!' * 20}"[:20]