Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Explained solution in Clear category for Cut Sentence by Selindian
def cut_sentence(line: str, length: int) -> str:
'''
Cut a given sentence, so it becomes shorter than or equal to a given length.
'''
# your code here
if len(line) <= length: # If text shorter or equal length:
return line # ... just return it.
else: # Else:
spaces = line[:length].count(' ') # ... Count all spaces between start and end (length) to get full words.
if line[length] == ' ': spaces += 1 # ... If last char is ' ' increment spaces by one. Otherwise we'll miss a word.
splitted = line.split() # ... Split text into signle word elements.
text = ' '.join(splitted[0:spaces]) + '...' # ... Join as many element as we have found spaces and add '...' at the end.
return text
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert cut_sentence("Hi my name is Alex", 4) == "Hi...", "First"
assert cut_sentence("Hi my name is Alex", 8) == "Hi my...", "Second"
assert cut_sentence("Hi my name is Alex", 18) == "Hi my name is Alex", "Third"
assert cut_sentence("Hi my name is Alex", 20) == "Hi my name is Alex", "Fourth"
print('Done! Do you like it? Go Check it!')
Feb. 28, 2022