How to do string formatting with placeholders in Java (like in Python)?

前端 未结 5 1021
南笙
南笙 2020-12-08 09:55

I am new to Java and am from Python. In Python we do string formatting like this:

>>> x = 4
>>> y = 5
>>> print(\"{0} + {1} = {2}\         


        
5条回答
  •  醉话见心
    2020-12-08 10:36

    If you want to use empty placeholders (without positions), you could write a small utility around Message.format(), like this

        void print(String s, Object... var2) {
            int i = 0;
            while(s.contains("{}")) {
                s = s.replaceFirst(Pattern.quote("{}"), "{"+ i++ +"}");
            }
            System.out.println(MessageFormat.format(s, var2));
        }
    

    And then, can use it like,

    print("{} + {} = {}", 4, 5, 4 + 5);
    

提交回复
热议问题