Named placeholders in string formatting

后端 未结 20 1945
情话喂你
情话喂你 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:14

    Thanks for all your help! Using all your clues, I've written routine to do exactly what I want -- python-like string formatting using dictionary. Since I'm Java newbie, any hints are appreciated.

    public static String dictFormat(String format, Hashtable<String, Object> values) {
        StringBuilder convFormat = new StringBuilder(format);
        Enumeration<String> keys = values.keys();
        ArrayList valueList = new ArrayList();
        int currentPos = 1;
        while (keys.hasMoreElements()) {
            String key = keys.nextElement(),
            formatKey = "%(" + key + ")",
            formatPos = "%" + Integer.toString(currentPos) + "$";
            int index = -1;
            while ((index = convFormat.indexOf(formatKey, index)) != -1) {
                convFormat.replace(index, index + formatKey.length(), formatPos);
                index += formatPos.length();
            }
            valueList.add(values.get(key));
            ++currentPos;
        }
        return String.format(convFormat.toString(), valueList.toArray());
    }
    
    0 讨论(0)
  • 2020-11-27 11:14

    I am the author of a small library that does exactly what you want:

    Student student = new Student("Andrei", 30, "Male");
    
    String studStr = template("#{id}\tName: #{st.getName}, Age: #{st.getAge}, Gender: #{st.getGender}")
                        .arg("id", 10)
                        .arg("st", student)
                        .format();
    System.out.println(studStr);
    

    Or you can chain the arguments:

    String result = template("#{x} + #{y} = #{z}")
                        .args("x", 5, "y", 10, "z", 15)
                        .format();
    System.out.println(result);
    
    // Output: "5 + 10 = 15"
    
    0 讨论(0)
提交回复
热议问题