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

前端 未结 5 1019
南笙
南笙 2020-12-08 09:55

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}\         


        
5条回答
  •  误落风尘
    2020-12-08 10:28

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

提交回复
热议问题