How to Print Curly-Brace Characters in a String While Using .Format

How do I print curly-brace characters in a string while using .format?

You need to double the {{ and }}:

>>> x = " {{ Hello }} {0} "
>>> print(x.format(42))
' { Hello } 42 '

Here's the relevant part of the Python documentation for format string syntax:

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 }}.

f-string with curly brace and function

You need a triple curly. Each double curly makes for a single escaped curly braces:

>>> f"{{{1}}}"
'{1}'

Python string formatting issue with curly braces ({ and })

Use double-curly-brace instead of single-curly-brace to write a literal curly-brace in an f-string:

dev_id = 1
query = f"""
{{
scripts(developers: "{dev_id}") {{

...
...
}}
}}
"""
print(query)
# {
# scripts(developers: "1") {
#
# ...
# ...
# }
# }

What do empty curly braces mean in a string?

Empty braces are equivalent to numeric braces numbered from 0:

>>> '{}: {}'.format(1,2)
'1: 2'
>>> '{0}: {1}'.format(1,2)
'1: 2'

Just a shortcut.

But if you use numerals you can control the order:

>>> '{1}: {0}'.format(1,2)
'2: 1'

Or the number of times something is used:

>>> '{0}: {0}, {1}: {1}'.format(1,2)
'1: 1, 2: 2'

Which you cannot do with empty braces.

.format() string, keep curly brackets if no match available

In case you don't want to convert {} to {{}}, I suggest you using Template from string. Its interface allows you to custom the formatting options as I did below:

from string import Template


class MyTemplate(Template):
delimiter = ""


dct_mapper = dict(a=1)
s = MyTemplate('{key1: value2, key1: value2}; attrib1={a}; attrib2={b}')
print(s.safe_substitute(**dct_mapper))

The output is, as you wanted:
{key1: value2, key1: value2}; attrib1=1; attrib2={b}

Explanation:
By default i Template you format strings using $var instead of {var} so I changed the pattern of the variable name (after the $) to be ${var} and the delimiter itself to be "", so {var} is enough instead of ${var}.

Moreover, templates have safe_substitute which allows you to format only few variables in the entire string and it doesn't raise an error for non-existing variable formats.

Also, s.safe_substitute(**dct_mapper) can be changed into s.safe_substitute(dct_mapper) if you prefer this over that.

Escape curly brace '{' in String.Format

Use double braces {{ or }} so your code becomes:

sb.AppendLine(String.Format("public {0} {1} {{ get; private set; }}", 
prop.Type, prop.Name));

// For prop.Type of "Foo" and prop.Name of "Bar", the result would be:
// public Foo Bar { get; private set; }

Escaping curly braces in string to be formatted an undefined number of times

I put together a partialformat function (in python3.x) that overrides the string format method to allow you to format only those sections of the string that require formatting. edit: I've included a python 2 version as well.

## python 3x version
import string
from _string import formatter_field_name_split
################################################################################
def partialformat(s: str, recursionlimit: int = 10, **kwargs):
"""
vformat does the acutal work of formatting strings. _vformat is the
internal call to vformat and has the ability to alter the recursion
limit of how many embedded curly braces to handle. But for some reason
vformat does not. vformat also sets the limit to 2!

The 2nd argument of _vformat 'args' allows us to pass in a string which
contains an empty curly brace set and ignore them.
"""

class FormatPlaceholder(object):
def __init__(self, key):
self.key = key

def __format__(self, spec):
result = self.key
if spec:
result += ":" + spec
return "{" + result + "}"

def __getitem__(self, item):
return

class FormatDict(dict):
def __missing__(self, key):
return FormatPlaceholder(key)

class PartialFormatter(string.Formatter):
def get_field(self, field_name, args, kwargs):
try:
obj, first = super(PartialFormatter, self).get_field(field_name, args, kwargs)
except (IndexError, KeyError, AttributeError):
first, rest = formatter_field_name_split(field_name)
obj = '{' + field_name + '}'

# loop through the rest of the field_name, doing
# getattr or getitem as needed
for is_attr, i in rest:
if is_attr:
try:
obj = getattr(obj, i)
except AttributeError as exc:
pass
else:
obj = obj[i]

return obj, first

fmttr = PartialFormatter()
try:
fs, _ = fmttr._vformat(s, ("{}",), FormatDict(**kwargs), set(), recursionlimit)
except Exception as exc:
raise exc
return fs

edit: looks like python 2.x has some minor differences.

## python 2.x version
import string
formatter_field_name_split = str._formatter_field_name_split
def partialformat(s, recursionlimit = 10, **kwargs):
"""
vformat does the acutal work of formatting strings. _vformat is the
internal call to vformat and has the ability to alter the recursion
limit of how many embedded curly braces to handle. But for some reason
vformat does not. vformat also sets the limit to 2!

The 2nd argument of _vformat 'args' allows us to pass in a string which
contains an empty curly brace set and ignore them.
"""

class FormatPlaceholder(object):
def __init__(self, key):
self.key = key

def __format__(self, spec):
result = self.key
if spec:
result += ":" + spec
return "{" + result + "}"

def __getitem__(self, item):
return

class FormatDict(dict):
def __missing__(self, key):
return FormatPlaceholder(key)

class PartialFormatter(string.Formatter):
def get_field(self, field_name, args, kwargs):
try:
obj, first = super(PartialFormatter, self).get_field(field_name, args, kwargs)
except (IndexError, KeyError, AttributeError):
first, rest = formatter_field_name_split(field_name)
obj = '{' + field_name + '}'

# loop through the rest of the field_name, doing
# getattr or getitem as needed
for is_attr, i in rest:
if is_attr:
try:
obj = getattr(obj, i)
except AttributeError as exc:
pass
else:
obj = obj[i]

return obj, first

fmttr = PartialFormatter()
try:
fs = fmttr._vformat(s, ("{}",), FormatDict(**kwargs), set(), recursionlimit)
except Exception as exc:
raise exc
return fs

Usage:

class ColorObj(object):
blue = "^BLUE^"
s = '{"a": {"b": {"c": {"d" : {} {foo:<12} & {foo!r} {arg} {color.blue:<10} {color.pink} {blah.atr} }}}}'
print(partialformat(s, foo="Fooolery", arg="ARRrrrrrg!", color=ColorObj))

Output:

{"a": {"b": {"c": {"d" : {} Fooolery             & 'Fooolery' Fooolery ARRrrrrrg! ^BLUE^ {color.pink} {blah.atr} }}}}

format string inside curly brackets are replaced with one curly brackets

Sample Image

Thanks to Lidor-Dublin I got this link and found there the way to solve this problem, so my code now has been changed:
Sample Image
also noticed that f (fast) string is better than format()



Related Topics



Leave a reply



Submit