Named placeholders in string formatting

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

    There is Java Plugin to use string interpolation in Java (like in Kotlin, JavaScript). Supports Java 8, 9, 10, 11…​ https://github.com/antkorwin/better-strings

    Using variables in string literals:

    int a = 3;
    int b = 4;
    System.out.println("${a} + ${b} = ${a+b}");
    

    Using expressions:

    int a = 3;
    int b = 4;
    System.out.println("pow = ${a * a}");
    System.out.println("flag = ${a > b ? true : false}");
    

    Using functions:

    @Test
    void functionCall() {
        System.out.println("fact(5) = ${factorial(5)}");
    }
    
    long factorial(int n) {
        long fact = 1;
        for (int i = 2; i <= n; i++) {
            fact = fact * i;
        }
        return fact;
    }
    

    For more info, please read the project README.

提交回复
热议问题