-1

I want to add some text within two delimiters in a string.

Previous string:

'ABC [123]'

New string needs to be like this:

'ABC [123 sometext]'

How do I do that?

3 Answers3

1

slightly more versatile I'd say, without using replace:

s = 'ABC [123]'
insert = 'sometext'
insert_after = '123'
delimiter = ' '

ix = s.index(insert_after)
if ix != -1:
    s = s[:ix+len(insert_after)] + delimiter + insert + s[ix+len(insert_after):]
    # or with an f-string:
    # s = f"{s[:ix+len(insert_after)]}{delimiter}{insert}{s[ix+len(insert_after):]}"

print(s)
# ABC [123 sometext]

If the insert patterns get more complex, I'd also suggest to take a look at regex. If the pattern is simple however, not using regex should be the more efficient solution.

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
0

Most of these types of changes depend on prerequisite knowledge of string pattern.

In your case simple str.replace would do the trick.

varstr = 'ABC [123]';
varstr.replace(']',' sometext]');

You can profit a lot from str doc and diving into regex;

Danilo
  • 1,017
  • 13
  • 32
0

All the above answers are correct but if somehow you are trying to add a variable

variable_string = 'ABC [123]'
sometext = "The text you want to add"

variable_string = variable_string.replace("]", " " + sometext + "]")
print(variable_string)