0

I want to replace a text that has a start and an end with the text itself and a label:

def replace_at(label, start, end, txt):
    """Replace substring of txt from start to end with label"""
    return ''.join((txt[:start], label, txt[end:]))

In this way, I get the label in place of the text but would like the text too. So the current output for "Hi my name is", with name that is labelled, is:

Hi my LABEL is

And I would like

Hi my name LABEL is
  • 1
    What is the problem you are facing? I don’t see a question, only a series of statements. – S3DEV Jan 20 '23 at 11:24
  • It depends on how you call the function, and that call is missing in your question. For me it works with `replace_at("LABEL",11,10,"Hi my name is")` – Ocaso Protal Jan 20 '23 at 11:27
  • "In this way, I get the label in place of the text but would like the text too" Okay, so your approach is to take: everything before the original text; the replacement; and everything after the original text - and stick those things together. Right? Can you think of something else you could add to that group of things, in order to get the result you want? Alternately: can you think of a way to modify the "everything after the text" logic so that it includes the original text? – Karl Knechtel Jan 20 '23 at 11:33
  • Alternately: in the desired output, **everything that was in the input** is included, right? We're really just **inserting** something at the `end` point, right? Do we actually care about `start`? – Karl Knechtel Jan 20 '23 at 11:34

1 Answers1

0

You can use your function to achieve the desired result like this:

def replace_at(label, start, end, txt):
    """Replace substring of txt from start to end with label"""
    return ''.join((txt[:start], label, txt[end:]))

s = "Hi my name is"
label_text = " LABEL"
final_word = "name"
idx = s.index(final_word) + len(final_word)
print(replace_at(label_text, idx, idx, s))

With output:

Hi my name LABEL is

I used the syntax xs[3:3] = [1,2] that will insert [1,2] at the index 3.

Caridorc
  • 6,222
  • 2
  • 31
  • 46