Append or replace last x characters in string in pyhon

Question:

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.

Asked By: Malaber

||

Answers:

Slice and then append.

def append_or_replace(original_string: str, append: str):
    return original_string[:MAX_SIZE-len(append)] + append
Answered By: Unmitigated

I would do it like this:

MAX_SIZE = 32

def append_or_replace(part_1: str, part_2: str):
    if len(part_1) + len(part_2) > MAX_SIZE:
        part_1 = part_1[:MAX_SIZE-len(part_2)]
    return part_1 + part_2
Answered By: dkruit
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.