Named placeholders in string formatting

Andy picture Andy · Feb 18, 2010 · Viewed 176k times · Source

In Python, when formatting string, I can fill placeholders by name rather than by position, like that:

print "There's an incorrect value '%(value)s' in column # %(column)d" % \
  { 'value': x, 'column': y }

I wonder if that is possible in Java (hopefully, without external libraries)?

Answer

schup picture schup · Apr 27, 2012

StrSubstitutor of jakarta commons lang is a light weight way of doing this provided your values are already formatted correctly.

http://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/text/StrSubstitutor.html

Map<String, String> values = new HashMap<String, String>();
values.put("value", x);
values.put("column", y);
StrSubstitutor sub = new StrSubstitutor(values, "%(", ")");
String result = sub.replace("There's an incorrect value '%(value)' in column # %(column)");

The above results in:

"There's an incorrect value '1' in column # 2"

When using Maven you can add this dependency to your pom.xml:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.4</version>
</dependency>