Reputation:
Basically, I'm trying to templatize Latex code where I need to output strings like B_{i}
, and I'd like to call string formatting to change i
. But the problem is that using Python's string formatting - which uses tuples to denote arguments - has been causing me trouble when I want to maintain tuples in my outputted string.
EXAMPLE
Suppose I have:
subscript = "22"
value = "10"
stringy = "B_{{0}} = {1}".format(subscript, value)"
When I print stringy
I get:
B_{0} = 10
I'd like to get:
B_{22} = 10
Upvotes: 1
Views: 127
Reputation: 3077
You need one more pair of curly brackets:
subscript = "22"
value = "10"
stringy = "B_{{{0}}} = {1}".format(subscript, value)
print(stringy) # 'B_{22} = 10'
This is because you need double ("{{"
) to print a literal curly bracket.
The two on the outside print the literal {}
and the middle {0}
gets replaced by subscript
.
Upvotes: 1
Reputation: 184455
You're almost there. You correctly doubled up the {
and }
characters so that they appear literally in the formatted result. However, you now don't have any placeholder for the first value, which needs to be represented as {0}
in your format string.
So:
stringy = "B_{{{0}}} = {1}".format(subscript, value)
Upvotes: 2
Reputation: 78554
Double the outer braces to escape those, therefore making a total of 3 pairs:
stringy = "B_{{{0}}} = {1}".format(subscript, value)
print(stringy)
# B_{22} = 10
As seen in your current solution, the doubled braces {{...}}
are escaped and do not take part in the formatting. You therefore need to include that extra layer of braces.
Upvotes: 2
Reputation: 61063
print("B_{{{0}}} = {1}".format(subscript, value))
The {{
will print out a {
character in the output, so you need another {}
to actually access the variable
Upvotes: 2