简体   繁体   中英

Java: Equivalent to Python's str.format()

In Python, there is a very nice method which simplifies creation of strings, making their code beautiful and readable.

For example, the following code will print ExampleProgram -E- Cannot do something

print_msg('E', 'Cannot do something')
def print_msg(type, msg):
    print 'ExampleProgram -{0}- {1}'.format(type, msg)

Ie I can specify "slots" within the string, using the {x} syntax, where x is the parameter index, and then it returns an new string, in which it replaces these slots with the parameters passed to the .format() method.

Currently with my Java knowledge, I would implement such a method this ugly way:

void printMsg(String type, String msg) {
    System.out.println("ExampleProgram -" + type + "- " + msg);
}

Is there something equivalent to Python's .format() string method?

MessageFormat has the exact usage.

 int planet = 7;
 String event = "a disturbance in the Force";

 String result = MessageFormat.format(
     "At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.",
     planet, new Date(), event);

You can simple use {0123} without extras. The output is:

 At 12:30 PM on Jul 3, 2053, there was a disturbance in the Force on planet 7.
System.out.format("ExampleProgram - %s - %s ",type, msg);

You can use the format method from the System.out .

Then use the following:

 String output = String.format("ExampleProgram - %s - %s ", type, msg);

Here type and msg are of String type.

For any integer use %d , and floating point %f , and String %s .

You can find all the information about different way of formatting output in the java documentation. Formatting Numeric Print Output

例如:

String s = String.format("something %s","name");

how about System.out.printf()? then you can use c style formatting

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM