42

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user1757703
  • 2,925
  • 6
  • 41
  • 62

6 Answers6

66

The MessageFormat class looks like what you're after.

System.out.println(MessageFormat.format("{0} + {1} = {2}", x, y, x + y));
rgettman
  • 176,041
  • 30
  • 275
  • 357
12

Java has a String.format method that works similarly to this. Here's an example of how to use it. This is the documentation reference that explains what all those % options can be.

And here's an inlined example:

package com.sandbox;

public class Sandbox {

    public static void main(String[] args) {
        System.out.println(String.format("It is %d oclock", 5));
    }        
}

This prints "It is 5 oclock".

Community
  • 1
  • 1
Daniel Kaplan
  • 62,768
  • 50
  • 234
  • 356
  • 3
    This `%` based string formatting is similar to [old-style formatting](http://docs.python.org/2/tutorial/inputoutput.html#old-string-formatting) used in python, OP is using the [new-style string formatting](http://docs.python.org/2/library/string.html#formatspec) – Ashwini Chaudhary Jul 08 '13 at 22:57
  • Ah, from the question I didn't know he was putting that much emphasis on using curly brackets. I thought he just wanted a way to format a string without concatenating strings and variables together. – Daniel Kaplan Jul 08 '13 at 22:58
  • 1
    Thanks for the comment btw. Otherwise I wouldn't have understood why @rgettman was getting so many upvotes. – Daniel Kaplan Jul 08 '13 at 23:00
7

Slf4j has MessageFormatter.format() that accepts {} without the argument number, just like Python. Slf4j is a popular logging framework, but you don't have to use it for logging to use MessageFormatter.

proski
  • 3,603
  • 27
  • 27
2

You can do this (using String.format):

int x = 4;
int y = 5;

String res = String.format("%d + %d = %d", x, y, x+y);
System.out.println(res); // prints "4 + 5 = 9"

res = String.format("%d %d", x, y);
System.out.println(res); // prints "4 5"
jh314
  • 27,144
  • 16
  • 62
  • 82
2

If you want to use empty placeholders (without positions), you could write a small utility around Message.format(), like this

    void print(String s, Object... var2) {
        int i = 0;
        while(s.contains("{}")) {
            s = s.replaceFirst(Pattern.quote("{}"), "{"+ i++ +"}");
        }
        System.out.println(MessageFormat.format(s, var2));
    }

And then, can use it like,

print("{} + {} = {}", 4, 5, 4 + 5);
1

If you use Log4j 2 (log4j-api) then you can use ParameterizedMessage.

ParameterizedMessage.format("{} {}", new Object[] {x, y});

or

new ParameterizedMessage("{} {}", x, y).getFormattedMessage(); // there is trimming
Saljack
  • 2,072
  • 21
  • 24