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

user1757703 picture user1757703 · Jul 9, 2013 · Viewed 51.9k times · Source

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}".format(x, y, x + y))
4 + 5 = 9
>>> print("{} {}".format(x,y))
4 5

How do I replicate the same thing in Java?

Answer

rgettman picture rgettman · Jul 9, 2013

The MessageFormat class looks like what you're after.

System.out.println(MessageFormat.format("{0} + {1} = {2}", x, y, x + y));