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

前端 未结 5 993
南笙
南笙 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:21

    Slf4j has MessageFormatter.format() that accepts {} without the argument number, just like Python. Slf4j is a popular logging framework, but you don't have to use it for logging to use MessageFormatter.

    0 讨论(0)
  • 2020-12-08 10:28

    Java has a String.format method that works similarly to this. Here's an example of how to use it. This is the documentation reference that explains what all those % options can be.

    And here's an inlined example:

    package com.sandbox;
    
    public class Sandbox {
    
        public static void main(String[] args) {
            System.out.println(String.format("It is %d oclock", 5));
        }        
    }
    

    This prints "It is 5 oclock".

    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-12-08 10:37

    The MessageFormat class looks like what you're after.

    System.out.println(MessageFormat.format("{0} + {1} = {2}", x, y, x + y));
    
    0 讨论(0)
  • 2020-12-08 10:38

    You can do this (using String.format):

    int x = 4;
    int y = 5;
    
    String res = String.format("%d + %d = %d", x, y, x+y);
    System.out.println(res); // prints "4 + 5 = 9"
    
    res = String.format("%d %d", x, y);
    System.out.println(res); // prints "4 5"
    
    0 讨论(0)
提交回复
热议问题