Named placeholders in string formatting

后端 未结 20 2293
情话喂你
情话喂你 2020-11-27 10:16

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 c         


        
20条回答
  •  旧时难觅i
    2020-11-27 11:04

    This is an old thread, but just for the record, you could also use Java 8 style, like this:

    public static String replaceParams(Map hashMap, String template) {
        return hashMap.entrySet().stream().reduce(template, (s, e) -> s.replace("%(" + e.getKey() + ")", e.getValue()),
                (s, s2) -> s);
    }
    

    Usage:

    public static void main(String[] args) {
        final HashMap hashMap = new HashMap() {
            {
                put("foo", "foo1");
                put("bar", "bar1");
                put("car", "BMW");
                put("truck", "MAN");
            }
        };
        String res = replaceParams(hashMap, "This is '%(foo)' and '%(foo)', but also '%(bar)' '%(bar)' indeed.");
        System.out.println(res);
        System.out.println(replaceParams(hashMap, "This is '%(car)' and '%(foo)', but also '%(bar)' '%(bar)' indeed."));
        System.out.println(replaceParams(hashMap, "This is '%(car)' and '%(truck)', but also '%(foo)' '%(bar)' + '%(truck)' indeed."));
    }
    

    The output will be:

    This is 'foo1' and 'foo1', but also 'bar1' 'bar1' indeed.
    This is 'BMW' and 'foo1', but also 'bar1' 'bar1' indeed.
    This is 'BMW' and 'MAN', but also 'foo1' 'bar1' + 'MAN' indeed.
    

提交回复
热议问题