在Scala中更好的字符串格式 [英] Better String formatting in Scala
问题描述
如果有太多参数, String.format
很容易变得太混乱。有一个更强大的方式来格式化一个字符串。像这样:
This is#{number} string.format(number - > 1)
或者是因为类型问题( format
或者是更好的方法来做这件事情,比如说,我们可能需要做一个Map [String,Any],我不认为这会让事情变得更糟)。这是:
val number = 1
< plain>这是{number}字符串< / plain>文本
尽管会污染名称空间吗?
编辑:
虽然简单的pimping可能在许多情况下,我也寻找的东西在同一方向Python的 format()
(参见: http://docs.python.org/release/3.1.2/library/string.html#formatstrings )
在Scala 2.10中,您可以使用字符串插值
val height = 1.9d
val name =James
println(f $ name%s是$ height%2.2f米高)//詹姆士身高1.90米
With too many arguments, String.format
easily gets too confusing. Is there a more powerful way to format a String. Like so:
"This is #{number} string".format("number" -> 1)
Or is this not possible because of type issues (format
would need to take a Map[String, Any], I assume; don’t know if this would make things worse).
Or is the better way doing it like this:
val number = 1
<plain>This is { number } string</plain> text
even though it pollutes the name space?
Edit:
While a simple pimping might do in many cases, I’m also looking for something going in the same direction as Python’s format()
(See: http://docs.python.org/release/3.1.2/library/string.html#formatstrings)
In Scala 2.10 you can use string interpolation.
val height = 1.9d
val name = "James"
println(f"$name%s is $height%2.2f meters tall") // James is 1.90 meters tall
这篇关于在Scala中更好的字符串格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!