Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

I.e. 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?

like image 851
SomethingSomething Avatar asked Sep 02 '26 04:09

SomethingSomething


1 Answers

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.
like image 127
Joop Eggen Avatar answered Sep 03 '26 18:09

Joop Eggen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!