Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Cut Sentence by eegoldstraw
def cut_sentence(line, length):
'''
Cut a given sentence, so it becomes shorter than or equal to a given length.
'''
#if the phrase is shorter than length return all of it
if len(line)<=length:
return line
#split phrase into words
words=line.split(' ')
#if the first word is too long return ...
if len(words[0])>length:
return '...'
#create message including first word
mes=words[0]
#if word and a whitespace fit add it to message
#otherwise add ... and break loop
for word in words[1:]:
if len(mes)+1+len(word)<= length:
mes+=' '+word
else:
mes+='...'
break
return mes
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!')
April 6, 2020
Comments: