Named placeholders in string formatting

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

    I am the author of a small library that does exactly what you want:

    Student student = new Student("Andrei", 30, "Male");
    
    String studStr = template("#{id}\tName: #{st.getName}, Age: #{st.getAge}, Gender: #{st.getGender}")
                        .arg("id", 10)
                        .arg("st", student)
                        .format();
    System.out.println(studStr);
    

    Or you can chain the arguments:

    String result = template("#{x} + #{y} = #{z}")
                        .args("x", 5, "y", 10, "z", 15)
                        .format();
    System.out.println(result);
    
    // Output: "5 + 10 = 15"
    

提交回复
热议问题