'How to index a value into string when it has multiple curly braces and % [duplicate]

I want to place a value into a string, however I cannot access the string as a f-string because it has multiple curly braces, but also I cannot use the following %s to access a value in the string as it has multiple % operators.

Here's an example string:

string = '{{id,name,tagline,frequency,duration,price,formattedPrice,pricePerUnit,formattedPricePerUnit}oneTimePurchase{index}}priceRange(withSubscriptionPriceRange:true),@include(if:$withPriceRange){fromPriceFormatted}discount{mode,value}currency,weight,seoJson}}}&v=%7B%22slug%22%3A%22p8-by-olly-fathers%22%2C%22externalId%22%3A%22%22%2C%22withPriceRange%22%3Afalse%7D'

I wanted to include the following string:

firstRange

inside the following part of the string:

externalId%22%3A%22%2firstRange%2C%22withPriceRange%22%3Afalse%7D

I have tried using:

string % "firstRange"

Aftering inserting %s in the required position but I get the following error:

ValueError: unsupported format character 'B' (0x42)


Solution 1:[1]

By using double curly brackets you can "escape" them:

'{hi} {}'.format('hey') #don't use this, instead use:
'{{hi}} {}'.format('hey')

So for your case:

string = '{{{{id,name,{}#ADDEDTHISFORTESTINGtagline,frequency,duration,price,formattedPrice,pricePerUnit,formattedPricePerUnit}}oneTimePurchase{{index}}}}priceRange(withSubscriptionPriceRange:true),@include(if:$withPriceRange){{fromPriceFormatted}}discount{{mode,value}}currency,weight,seoJson}}}}}}&v=%7B%22slug%22%3A%22p8-by-olly-fathers%22%2C%22externalId%22%3A%22%22%2C%22withPriceRange%22%3Afalse%7D'

string = string.format('test')
print(string)

Output:

{{id,name,test#ADDEDTHISFORTESTINGtagline,frequency,duration,price,formattedPrice,pricePerUnit,formattedPricePerUnit}oneTimePurchase{index}}priceRange(withSubscriptionPriceRange:true),@include(if:$withPriceRange){fromPriceFormatted}discount{mode,value}currency,weight,seoJson}}}&v=%7B%22slug%22%3A%22p8-by-olly-fathers%22%2C%22externalId%22%3A%22%22%2C%22withPriceRange%22%3Afalse%7D

Notice that 'test' was added as the 3rd word in place of the two curly brackets I added:

'{}#ADDEDTHISFORTESTING' #this
#changed to:
'test#ADDEDTHISFORTESTING' #this
#via
string = string.format('test')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Eli Harold