Reputation: 53
I want to print the string: [{X}]
, while X is an int. when I'm using .format
I get into trouble with printing the char '{' because it's a part of the format.
I tried to use the code line:
print("[{{}}]".format(X))
and I get the error:
Single '}' encountered in format string.
Is there a way around this error?
Upvotes: 1
Views: 1351
Reputation: 12992
If using format()
isn't an absolute necessity, then you can do something like that:
x = 12
print("[{%i}]" %x)
# [{12}]
Which is way cleaner and more understandable than:
print("[{{{}}}]".format(X))
Upvotes: 0
Reputation: 531165
While I can't reproduce the error you claim, you only produce the characters needed to display the braces, with no replacement field.
fmt = "[" # the opening bracket
fmt += "{{" # the literal {
fmt += "{}" # the replacement field
fmt += "}}" # the literal }
fmt += "]" # the closing bracket
assert fmt == "[{{{}}}]"
# not "[{{}}]", as you have
assert fmt.format(3) == "[{3}]"
Upvotes: 1
Reputation: 20669
{{}}
are used to print {}
. If you want something like this {something}
. Try this
X=10
print("[{{{}}}]".format(X))
# [{10}]
Upvotes: 1