How to Escape % in String.Format

How to escape % in String.Format?

To escape %, you will need to double it up: %%.

escaping formatting characters in java String.format

You can just double up the %

Escape string for Lua's string.format

You can escape a % with another %, e.g. string.format("%%20") will give %20

How can I escape the format string?

A bit of a simpler workaround which I use:

my_string = 'Hello {name}, my name is {my_name}!'

to_replace = {
"search_for" : "replace_with",
"name" : "minerz029",
}

for search_str in to_replace:
my_string = my_string.replace('{' + search_str + '}', to_replace[search_str])

print(my_string)

This can be expanded easily with more keys in the to_replace dict and wont complain even if the search string doesn't exist. It could probably be improved to offer more of .format()'s features, but it was enough for me.

How to put unprocessed (escaped) words inside String.Format

You can surround literal strings with quotes, which for longer strings is probably easier and a bit more readable than escaping every character with a backslash:

str = String.Format("{0:MMM d 'at' m:mm"+yearStr+"}", dt);

See Custom Date and Time Format Strings in MSDN Library (search for "Literal string delimiter").

(And did you mean h:mm instead of m:mm?)

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}


Related Topics



Leave a reply



Submit