How to escape the "{" character in a formatted string?

Asked

Viewed 219 times

-1

How would it be possible to make a string that uses the . format accept the use of keys as elements of the string and not escape it.

Ex: I would like the variable s:

interface = "alguma"
s = """{INTERFACE} {""".format(INTERFACE=interface)

Receive:

alguma {

I appreciate any help.

1 answer

1


You need to duplicate the keys. Instead of just {, utilize {{:

interface = "alguma"
s = "{INTERFACE} {{".format(INTERFACE=interface)

print(s)  # alguma {

If you are using version 3.6 or higher of Python, give preferences to f-strings:

s = f'{interface} {{'

Note that it is basically the same syntax that is used with format, except by prefix f.

According to the official documentation:

Format strings contain "Replacement Fields" surrounded by Curly braces {}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a Brace Character in the literal text, it can be escaped by doubling: {{ and }}.

In free translation, strings formatted have replaceable fields surrounded by keys. Anything that is not between keys will be considered as literal text, which will be copied to the unmodified output. If you need to include the key character as literal text you can escape by duplicating it: {{ and }}.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.