2013-07-08 80 views
23

我是Java新手,來自Python。在Python中,我們這樣做字符串格式:Java:使用佔位符格式化字符串

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

如何在Java中複製相同的東西?

回答

45

MessageFormat類看起來像你以後

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

注意'MessageFormat.format'不能處理空的佔位符'{}'。 –

+0

...和警告,如果你使用''{'它不會識別括號 –

10

Java的String.format方法與此類似。 Here's an example of how to use it.這是解釋所有這些%選項可以是什麼的documentation reference

這裏是一個內嵌例如:

package com.sandbox; 

public class Sandbox { 

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

這版畫 「這是5點鐘」。

+1

這''%基於字符串格式類似於[舊式。在Python中使用的格式](http://docs.python.org/2/tutorial/inputoutput.html#old-string-formatting),OP使用[new-style string formatting](http://docs.python .org/2/library/string.html#formatspec) –

+0

啊,從這個問題我不知道他把那麼多的emp hasis使用大括號。我以爲他只是想要一種格式化字符串而不將字符串和變量連接起來的方式。 –

+1

感謝評論btw。否則,我不會明白爲什麼@rgettman得到這麼多upvotes。 –

3

您可以(使用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"