Named placeholders in string formatting

后端 未结 20 2310
情话喂你
情话喂你 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 values) {
        StringBuilder convFormat = new StringBuilder(format);
        Enumeration 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());
    }
    

提交回复
热议问题