Named Placeholders in String Formatting

Named placeholders in string formatting

Thanks for all your help! Using all your clues, I've written routine to do exactly what I want -- python-like string formatting using dictionary. Since I'm Java newbie, any hints are appreciated.

public static String dictFormat(String format, Hashtable<String, Object> values) {
StringBuilder convFormat = new StringBuilder(format);
Enumeration<String> keys = values.keys();
ArrayList valueList = new ArrayList();
int currentPos = 1;
while (keys.hasMoreElements()) {
String key = keys.nextElement(),
formatKey = "%(" + key + ")",
formatPos = "%" + Integer.toString(currentPos) + "$";
int index = -1;
while ((index = convFormat.indexOf(formatKey, index)) != -1) {
convFormat.replace(index, index + formatKey.length(), formatPos);
index += formatPos.length();
}
valueList.add(values.get(key));
++currentPos;
}
return String.format(convFormat.toString(), valueList.toArray());
}

Is there a String.Format that can accept named input parameters instead of index placeholders?

In C# 6 you can use string interpolation:

string name = "Lisa";
int age = 20;
string str = $"Her name is {name} and she's {age} years old";

As Doug Clutter mentioned in his comment, string interpolation also supports format string. It's possible to change the format by specifying it after a colon. The following example will output a number with a comma and 2 decimal places:

var str = $"Your account balance is {balance:N2}"

As Bas mentioned in his answer, string interpolation doesn't support template string. Actually, it has no built in support for that. Fortunately it exists in some great libraries.


SmartFormat.NET for example has support for named placeholders:

Smart.Format("{Name} from {Address.City}, {Address.State}", user)

// The user object should at least be like that

public class User
{
public string Name { get; set; }
public Address Address { get; set; }
}

public class Address
{
public string City { get; set; }
public string State { get; set; }
}

It is available on NuGet and has excellent documentation.


Mustache is also a great solution. Bas has described its pros well in his answer.

Python string formatting - combine named placeholder and float formatter for the same argument?

'{value:.2f}'.format(value=pi)

String formatting named parameters?

Solution in Python 3.6+

Python 3.6 introduces literal string formatting, so that you can format the named parameters without any repeating any of your named parameters outside the string:

print(f'<a href="{my_url:s}">{my_url:s}</a>')

This will evaluate my_url, so if it's not defined you will get a NameError. In fact, instead of my_url, you can write an arbitrary Python expression, as long as it evaluates to a string (because of the :s formatting code). If you want a string representation for the result of an expression that might not be a string, replace :s by !s, just like with regular, pre-literal string formatting.

For details on literal string formatting, see PEP 498, where it was first introduced.

Java string templatizer / formatter with named arguments

You might also try org.apache.commons.lang3.text.StrSubstitutor if Java 7 is not an option. It does exactly what you want it to do. Whether it’s light-weight might depend on whether you use something else of commons-lang as well.

How to dynamically inspect a format string with named placeholders like {foo} {bar} {baz}

Yes, you can use the built-in parser:

>>> var = '''{foo} {bar} {baz}'''
>>> import string
>>> formatter = string.Formatter()
>>> formatter.parse(var)
<formatteriterator object at 0x109174750>
>>> list(formatter.parse(var))
[('', 'foo', '', None), (' ', 'bar', '', None), (' ', 'baz', '', None)]

Java generating Strings with placeholders

See String.format method.

String s = "hello %s!";
s = String.format(s, "world");
assertEquals(s, "hello world!"); // should be true

Named string formatting in C#

There is no built-in method for handling this.

Here's one method

string myString = "{foo} is {bar} and {yadi} is {yada}".Inject(o);

Here's another

Status.Text = "{UserName} last logged in at {LastLoginDate}".FormatWith(user);

A third improved method partially based on the two above, from Phil Haack



Related Topics



Leave a reply



Submit