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?
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?
 
    
    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.
 
    
    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)
