Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Find last space and slice solution in Clear category for Cut Sentence by kudinov.feodor
def cut_sentence(line, length):
'''
Cut a given sentence, so it becomes shorter than or equal to a given length.
'''
if len(line) <= length:
return line
last_space = line.rfind(" ", 0, length + 1)
res = line[:last_space] if last_space > 0 else ""
return res + "..."
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!')
Nov. 10, 2019
Comments: