字符串格式化中的命名占位符 [英] Named placeholders in string formatting

查看:125
本文介绍了字符串格式化中的命名占位符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,格式化字符串时,我可以按名称而不是按位置填充占位符,如:

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 }

我想知道Java是否可行(希望没有外部库)?

I wonder if that is possible in Java (hopefully, without external libraries)?

推荐答案

感谢您的帮助!使用你所有的线索,我写了例行程序来做我想要的 - 使用字典的类似python的字符串格式。由于我是Java新手,任何提示都很受欢迎。

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());
}

这篇关于字符串格式化中的命名占位符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆