2013-07-08 26 views
23

Sono nuovo di Java e di Python. In Python facciamo una formattazione di stringhe come questa:Java: formattazione di stringhe con segnaposto

>>> x = 4 
>>> y = 5 
>>> print("{0} + {1} = {2}".format(x, y, x + y)) 
4 + 5 = 9 
>>> print("{} {}".format(x,y)) 
4 5 

Come si replica la stessa cosa in Java?

risposta

45

La classe MessageFormat assomiglia a quello che stai dopo

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

Con l'avvertimento che 'MessageFormat.format' non gestisce il segnaposto vuoto' {} '. –

+0

... e l'avvertenza che se usi ''{' non riconoscerà le parentesi –

10

Java ha un metodo String.format che funziona in modo simile a questo. Here's an example of how to use it. Questo è il documentation reference che spiega cosa possono essere tutte quelle opzioni %.

Ed ecco un esempio inline:

package com.sandbox; 

public class Sandbox { 

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

Questo stampa "E '5 in punto".

+1

Questo '%' formattazione corda a base è simile a [vecchio stile. formattazione] (http://docs.python.org/2/tutorial/inputoutput.html#old-string-formatting) usato in python, OP sta usando la [nuova formattazione della stringa] (http: //docs.python .org/2/library/string.html # formatspec) –

+0

Ah, dalla domanda non sapevo che stava mettendo così tanto emp hasis sull'uso di parentesi graffe. Ho pensato che voleva solo un modo per formattare una stringa senza concatenare stringhe e variabili insieme. –

+1

Grazie per il commento btw. Altrimenti non avrei capito perché @rgettman stava ottenendo così tanti upvotes. –

3

È possibile farlo (usando 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" 
Problemi correlati