Home > Enterprise >  How to insert a string after a specific closing curly brace in Python?
How to insert a string after a specific closing curly brace in Python?

Time:10-06

I'm trying to insert a sub string right after a specific closing curly brace of a string.

For example let's say the full string looks like following:

"{records#QUERY# { edges { node { id legalname countryiso naicscode naicsdescription } } <need to place another string here> } }"

So I'd need to like append a string in that place holder <> above (please note that in the original string this place holder won't be provided).

Basically I need to find out the closing curly brace of the second opening curly brace and place it before that.

Any help or pointers could be appreciated.

CodePudding user response:

Hi| Is the end always the same ? "}} }}" if so you can remove it and add it witht he new text.

text = "{records#QUERY# { edges { node { id legalname countryiso naicscode naicsdescription } } } }"
text_split = ss.strip("} }")

new_text2 = text_split ("} } New Text Inserted } }")

CodePudding user response:

Dini's answer is practical, but if you want to use regex for this purpose, one solution may be:

import re
string = "{records#QUERY# { edges { node { id legalname countryiso naicscode naicsdescription } } <need to place another string here> } }"
match = re.search("\{.*?\{.*?\{.*?\{.*?\}.*?(\}).*?(\}).*?\}",string)

idx1 = match.span(1)[0] # index of second "}"
idx2 = match.span(2)[0] # index of third "}"

string = string[:idx1 1]   " "   "apple"   " "   string[idx2:]
print(string)

Output is:

{records#QUERY# { edges { node { id legalname countryiso naicscode naicsdescription } } apple } }

CodePudding user response:

I managed to resolve this by finding the indices of the second close curly brace from last and the third and placed the string in between them:

fetcher_query = "{records#QUERY# { edges { node { id legalname countryiso naicscode naicsdescription}}}}"
    
close_curly_brace_iterator = re.finditer(r"}", fetcher_query)
indices = [m.start(0) for m in close_curly_brace_iterator]

third_before_last_idx = indices[-2]  # index of third from last }
second_before_last_idx = indices[-3]  # index of second from last }

fetcher_query = fetcher_query[:third_before_last_idx]   " "   "pageInfo {endCursor hasNextPage}"   " "   fetcher_query[second_before_last_idx:-1]
logger.info(f'updated fetcher query with graphql pagination: {fetcher_query}')
  • Related