EDIT: I didn't even think about the "..." being part of n. Sorry, guys! (and thank you)
I'm not sure if the "question" is missing something, or if I'm missing something. I am supposed to write a function in python that returns truncated-at-n-chars version of phrase. The docstring is as follows:
"""Return truncated-at-n-chars version of phrase.
If the phrase is longer than n, make sure it ends with '...' and is no
longer than n.
>>> truncate("Hello World", 6)
'Hel...'
>>> truncate("Problem solving is the best!", 10)
'Problem...'
>>> truncate("Yo", 100)
'Yo'
The smallest legal value of n is 3; if less, return a message:
>>> truncate('Cool', 1)
'Truncation must be at least 3 characters.'
>>> truncate("Woah", 4)
'W...'
>>> truncate("Woah", 3)
'...'
"""
Solution is:
if n < 3:
return "Truncation must be at least 3 characters."
if n > len(phrase) + 2:
return phrase
return phrase[:n - 3] + "..."
So why is it n-3? Is it because it says "The smallest legal value of n is 3"? Because when I google it, less than 3 is possible. Even if it wasn't, why isn't it just return phrase[:n] + "..."?
The reason why the solution includes n-3 is because you have to make sure that you leave 3 characters from the end so that you can add on the "...". For example, if you had the word "Elephant" and you had to truncate it at 5 characters. The input would look something like this
truncate("Elephant", 5)
and the output would look like this
'El...'
As you can see, I am not using the first 5 characters of the word 'Elephant,' but rather only the first 2, because each dot (.) counts as a character as well, so I must subtract 3 from n to count each dot (.) as well. Hope this answers your question!