Scala 中更好的字符串格式 [英] Better String formatting in Scala

查看:19
本文介绍了Scala 中更好的字符串格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果参数太多,String.format 很容易变得过于混乱.有没有更强大的方法来格式化字符串.像这样:

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)

或者这不可能是因为类型问题(我认为 format 需要使用 Map[String, Any];不知道这是否会使事情变得更糟).

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?

虽然在许多情况下可能会进行简单的拉皮条,但我也在寻找与 Python 的 format() 方向相同的东西(参见:http://docs.python.org/release/3.1.2/library/string.html#formatstrings)

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)

推荐答案

在 Scala 2.10 中你可以使用 字符串插值.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆