for example

'I am very {dfghjk} good boy.' 

It is necessary to somehow remove the element {dfghjk} Its length and location do not matter: it can be located at the beginning or end of a line and consist of one or more characters.

Expected Result:

 'I am very good boy.' 
  • Can there be nested / unbalanced elements? For example, what result do you expect for: "}{{a{b{c}d}e}f" ? - jfs
  • @jfs Denmark with which I work, do not have in myself something like that. So I don’t even know what to say :) - Bernard
  • This means that there are no nested brackets. - jfs

2 answers 2

Use regular expressions ( Regular Expressions AKA RegEx ):

 In [120]: import re In [121]: s Out[121]: '{Am} I am very {bad} good {girl} boy.' In [122]: re.sub(r'{[^\}]+}', '', s) Out[122]: ' I am very good boy.' 

to remove extra spaces:

 In [125]: re.sub('\s+', ' ', re.sub(r'{[^\}]+}', '', s)).strip() Out[125]: 'I am very good boy.' 

    better by regular expressions, but as an option

     def format_from_kwargs(arg: str, **kwargs) -> str: try: return arg.format(**kwargs) except KeyError as ex: kwargs[ex.args[0]] = '' return format_from_kwargs(arg, **kwargs) print(format_from_kwargs('I am very {dfghjk} good boy. {qwe}')) 
    • it breaks for '{error! element}' '{error! element}' . And even when it works for simple lines, to put it mildly, this is not a recommended option (it’s like glueing wallpaper through a keyhole). - jfs