2015-10-22 109 views
2

在Python中,有一個非常好的方法可以簡化字符串的創建,使它們的代碼更加美觀和可讀。Java:相當於Python的str.format()

例如,下面的代碼將打印ExampleProgram -E- Cannot do something

print_msg('E', 'Cannot do something') 
def print_msg(type, msg): 
    print 'ExampleProgram -{0}- {1}'.format(type, msg) 

即我可以使用{x}語法在字符串中指定「插槽」,其中x是參數索引,然後它返回一個新字符串,其中它將使用傳遞給.format()方法的參數替換這些插槽。

與我的Java知識

目前,我會實現這樣的方法這種醜陋的方式:

void printMsg(String type, String msg) { 
    System.out.println("ExampleProgram -" + type + "- " + msg); 
} 

有什麼等同於Python的.format()字符串的方法?

回答

6

MessageFormat有確切的用法。

int planet = 7; 
String event = "a disturbance in the Force"; 

String result = MessageFormat.format(
    "At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.", 
    planet, new Date(), event); 

您可以簡單地使用{0123}沒有額外的。 輸出結果爲:

At 12:30 PM on Jul 3, 2053, there was a disturbance in the Force on planet 7. 
4

例如:

String s = String.format("something %s","name"); 
+0

謝謝!看起來很相似。 Python只接受字符串 - 看起來就像你的例子一樣,我可以使用'%s'然後傳遞字符串。這裏唯一的缺點是,如果我想在字符串中多次重複相同的值,我必須一次又一次地通過它,而在Python中,我可以重複插槽'{0} {0}' – SomethingSomething

+1

@SomethingSomething您可以在Java中做類似的事情;請查看['java.util.Formatter'](https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html)以獲取示例。 – TNT

5
System.out.format("ExampleProgram - %s - %s ",type, msg); 

您可以使用從System.out格式的方法。

然後使用以下:

String output = String.format("ExampleProgram - %s - %s ", type, msg); 

這裏typemsgString類型。

對於任何整數使用%d和浮點數%fString%s

您可以在java文檔中找到關於輸出格式不同的所有信息。 Formatting Numeric Print Output

+0

謝謝。如果我想將它存儲在一個新的字符串中呢? – SomethingSomething

+1

@SomethingSomething我已經更新了答案,請檢查。它還包括到java文檔的鏈接。 – YoungHobbit

1

System.out.printf()怎麼樣?那麼你可以使用c風格格式

+1

謝謝!我更喜歡某種格式,我可以多次重複插槽的索引,並且只使用字符串。這也是一個不錯的解決方案 – SomethingSomething