I have a string with a max length of 32. I want to automatically append "_deleted" to it. When the string is so long that it + "_deleted" would be longer than 32 I want to replace as little characters as possible, so that the resulting string is 32 chars long and ends in "_deleted".
How would you do that elegantly in python?
What I came up with so far:
MAX_SIZE = 32
def append_or_replace(original_string: str, append: str):
result_length = len(original_string) + len(append)
if result_length >= MAX_SIZE:
remove_characters = result_length - MAX_SIZE
return original_string[:-remove_characters] + append
else:
return original_string + append
This seems way to complicated for such a simple problem. How can I improve it?
In reality the string is way longer and I want to append something else, so that is why the example may seem a bit weird, I tried to minimalize the problem.