Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Uncategorized category for Cut Sentence by Rafal.Keszycki
def cut_sentence(sentence: str, max_length: int) -> str:
if len(sentence) <= max_length:
return sentence
else:
if max_length <= 3:
return "..."
else:
last_space = sentence.rfind(" ", 0, max_length +1)
if last_space == -1:
return sentence[:max_length-3] + "..."
else:
return sentence[:last_space] + "..."
print("Example:")
print(cut_sentence("Hi my name is Alex", 4))
# These "asserts" are used for self-checking
assert cut_sentence("Hi my name is Alex", 8) == "Hi my..."
assert cut_sentence("Hi my name is Alex", 4) == "Hi..."
assert cut_sentence("Hi my name is Alex", 20) == "Hi my name is Alex"
assert cut_sentence("Hi my name is Alex", 18) == "Hi my name is Alex"
print("The mission is done! Click 'Check Solution' to earn rewards!")
Jan. 21, 2023