Source From Here
Question
In Python, when formatting string, I can fill placeholders by name rather than by position, like that:
I wonder if that is possible in Java (
hopefully, without external libraries)? Thanks in advance.
How-To
StrSubstitutor of jakarta commons lang is a light weight way of doing this provided your values are already formatted correctly. Sample code as below:
Output:
Question
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 }
How-To
StrSubstitutor of jakarta commons lang is a light weight way of doing this provided your values are already formatted correctly. Sample code as below:
- Map
values = new HashMap(); - values.put("value", 1);
- values.put("column", 2);
- StrSubstitutor sub = new StrSubstitutor(values, "%(", ")");
- printf("%s\n", sub.replace("There's an incorrect value '%(value)' in column # %(column)"))
沒有留言:
張貼留言