Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 678
user1757703 Avatar asked Jul 08 '13 22:07

user1757703


2 Answers

The MessageFormat class looks like what you're after.

System.out.println(MessageFormat.format("{0} + {1} = {2}", x, y, x + y)); 
like image 140
rgettman Avatar answered Sep 20 '22 22:09

rgettman


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".

like image 33
Daniel Kaplan Avatar answered Sep 19 '22 22:09

Daniel Kaplan