Skip to content Skip to sidebar Skip to footer

Python String 'template' Equivalent In Java

Python supports the following operation: >>> s = Template('$who likes $what') >>> s.substitute(who='tim', what='kung pao') 'tim likes kung pao' (Example taken fr

Solution 1:

Take a look at http://www.stringtemplate.org/. Here is an example:

ST hello = new ST("Hello, <name>");
hello.add("name", "World");
System.out.println(hello.render());

prints out:

"Hello World"

Solution 2:

Chunk templates (http://www.x5dev.com/chunk) make this kind of thing pretty easy:

Chunk c = new Chunk();
c.append("{$who} likes {$what}");
c.set("who", "tim");
c.set("what", "kung pao");
String output = c.toString();

Or if you have a Map<String,String> already:

Chunk c = new Chunk();
c.append("{$who} likes {$what}");
Map<String,String> tagValues = getTagValues();
c.setMultiple(tagValues);
c.render(System.out);

Chunk also makes it easy to load templates from a file or a group of files, and supports looping, branching, and presentation filters.

Solution 3:

I don't know if there is anything equal, but you can do:

String s = "$who likes $what";
s.replace("$who", "tim").replace("$what", "kung pao");

And you will get the same result.

Solution 4:

There's another option answered here. Will repeat it for convenience.

There's a library org.apache.commons:commons-text:1.9 with class StringSubstitutor. That's how it works:

// Build mapMap<String, String> valuesMap = newHashMap<>();
 valuesMap.put("animal", "quick brown fox");
 valuesMap.put("target", "lazy dog");
 String templateString = "The ${animal} jumped over the ${target}.";

 // Build StringSubstitutorStringSubstitutor sub = newStringSubstitutor(valuesMap);

 // ReplaceString resolvedString = sub.replace(templateString);

Still there's a remark. StringSubstitutor instance is created with a substitution map and then parses template strings with its replace method. That means it cannot pre-parse the template string, so processing the same template with different substitution maps may be less efficient.

The Python's string.Template works the opposite way. It's created with the template string and then processes substitution maps with its substitute or safe_substitute methods. So theoretically it can pre-parse the template string that may give some performance gain.

Also the Python's string.Template will process ether $variable or ${variable} by default. Couldn't find so far how to adjust the StringSubstitutor to do this way.

By default StringSubstitutor parses placeholders in the values that may cause infinite loops. stringSubstitutor.setDisableSubstitutionInValues(true) will disable this behavior.

Solution 5:

String s = String.format("%s likes %s", "tim", "kung pao");

or

System.out.printf("%s likes %s", "tim", "kung pao");

you can easily do the templating with this too.

String s = "%s likes %s";
String.format(s, "tim", "kung pao");

Post a Comment for "Python String 'template' Equivalent In Java"