0

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.

Malaber
  • 57
  • 1
  • 8
  • There isn't anything specially built for it. Simplifying the logic seems more like a question for [codereview.se] to me. – Karl Knechtel Jan 24 '23 at 15:46
  • Does this answer your question? [Python truncate a long string](https://stackoverflow.com/questions/2872512/python-truncate-a-long-string) – JonSG Jan 24 '23 at 15:57
  • @JonSG Not really, I am already doing truncation in my code example. [Unmitigated's answer](https://stackoverflow.com/a/75223834/10559526) is basically what I was looking for though. – Malaber Jan 24 '23 at 16:24

2 Answers2

4

Slice and then append.

def append_or_replace(original_string: str, append: str):
    return original_string[:MAX_SIZE-len(append)] + append
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • 1
    The key idea here is that `original_string[:MAX_SIZE]` doesn't cause an error for *shorter* strings, and just gives the original unmodified. This allows us to avoid the conditional logic. – Karl Knechtel Jan 24 '23 at 15:48
0

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
dkruit
  • 135
  • 6