Escape Curly Brace '{' in String.Format

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

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

How to escape braces (curly brackets) in a format string in .NET

For you to output foo {1, 2, 3} you have to do something like:

string t = "1, 2, 3";
string v = String.Format(" foo {{{0}}}", t);

To output a { you use {{ and to output a } you use }}.

Or now, you can also use C# string interpolation like this (a feature available in C# 6.0)

Escaping brackets: String interpolation $(""). It is new feature in C# 6.0.

var inVal = "1, 2, 3";
var outVal = $" foo {{{inVal}}}";
// The output will be: foo {1, 2, 3}

escape curly braces { in a string to support String.Format

How about this:

string input = "Hello {0}, please refer for more information {or contact us at: XXXX}";
Regex rgx = new Regex("(\\{(?!\\d+})[^}]+})");
string replacement = "{$1}";
string result = rgx.Replace(input, replacement);

Console.WriteLine("String {0}", result);

// Hello {0}, please refer for more information {{or contact us at: XXXX}}

... assuming that the only strings that should not be escaped are of format {\d+}.

There are two caveats here. First, we may encounter already-escaped curvy braces - {{. Fix for it is more-o-less easy: add more lookarounds...

Regex rgx = new Regex("(\\{(?!\\d+})(?!\\{)(?<!\\{\\{)[^}]+})");

... in other words, when trying to replace a bracket, make sure it's a lonely one. )

Second, formats themselves may not be so simple - and as the complexity of those that actually may be present in your strings grows, so does the regex's one. For example, this little beasty won't attempt to fix format string that start with numbers, then go all the way up to } symbol without any space in between:

Regex rgx = new Regex("(\\{(?!\\d\\S*})(?!\\{)(?<!\\{\\{)[^}]+})");

As a sidenote, even though I'm the one of those people that actually like to have two problems (well, sort of), I do shudder when I look at this.

UPDATE: If, as you said, you need to escape each single occurrence of { and }, your task is actually a bit easier - but you will need two passes here, I suppose:

Regex firstPass = new Regex("(\\{(?!\\d+[^} ]*}))");
string firstPassEscape = "{$1";
...
Regex secondPass = new Regex("((?<!\\{\\d+[^} ]*)})");
string secondPassEscape = "$1}";

How to escape curly-brackets in f-strings?

Although there is a custom syntax error from the parser, the same trick works as for calling .format on regular strings.

Use double curlies:

>>> foo = 'test'
>>> f'{foo} {{bar}}'
'test {bar}'

It's mentioned in the spec here and the docs here.

How to escape curly braces in a format string in Rust

You might be reading some out of date docs (e.g. for Rust 0.9)

As of Rust 1.0, the way to escape { and } is with another { or }

write!(f, "{{ hash:{}, subject: {} }}", self.hash, self.subject)

The literal characters { and } may be included in a string by
preceding them with the same character. For example, the { character
is escaped with {{ and the } character is escaped with }}.

C# String.Format with Curly Bracket in string

You can escape the braces by doubling them up in your format strings:

string.Format("{{ foo: '{0}', bar: '{1}' }}", foo, bar);

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

escape for { inside C# 6 string interpolation

Type { twice to escape it:

$"if(inErrorState){{send 1, \"{val}\" }}"

BTW you can do the same with double quotes.

Curly braces with f-strings - ValueError: Sign not allowed in string format specifier

Escape the braces like this.

>>> f'{{"c": {a}}}'
'{"c": 0}'


Related Topics



Leave a reply



Submit