Named placeholders in string formatting

后端 未结 20 2291
情话喂你
情话喂你 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条回答
  •  南笙
    南笙 (楼主)
    2020-11-27 11:09

    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 values = new HashMap();
    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:

    
        org.apache.commons
        commons-lang3
        3.4
    
    

提交回复
热议问题