[英]string format in Scala
New to Scala and see people are using sign f
ahead of a string, here is an example I tried which works. 是Scala的新手,看到人们在字符串前面使用符号
f
,这是我尝试的有效示例。 Wondering what is the function of sign f
? 想知道符号
f
的作用是什么? Does it need to be combined to use with %s? 是否需要与%s结合使用? Tried to search some tutorials but failed.
试图搜索一些教程,但失败了。 Thanks.
谢谢。
object HelloWorld {
def main(args: Array[String]) {
var start = "Monday";
var end = "Friday";
var palindrome = "Dot saw I was Tod";
println(f"date >= $start%s and date <= $end%s" + palindrome);
// output date >= Monday and date <= FridayDot saw I was Tod
}
}
http://docs.scala-lang.org/overviews/core/string-interpolation.html http://docs.scala-lang.org/overviews/core/string-interpolation.html
The f Interpolator
f内插器
Prepending f to any string literal allows the creation of simple formatted strings, similar to printf in other languages.
在任何字符串文字前加上f可以创建简单格式的字符串,类似于其他语言中的printf。 When using the f interpolator, all variable references should be followed by a printf-style format string, like %d.
使用f插值器时,所有变量引用都应后跟一个printf样式的格式字符串,例如%d。
PS. PS。 another somewhat related feature is http://docs.scala-lang.org/overviews/quasiquotes/expression-details
另一个有点相关的功能是http://docs.scala-lang.org/overviews/quasiquotes/expression-details
See the explanation here . 请参阅此处的说明。 For people coming from C the
f
interpolator is a printf
style formatter. 对于来自C的人们,
f
插值器是printf
样式格式化程序。 %
is to denote the type of data and with a $
you may may refer to a previously defined variable. %
表示数据类型,使用$
可以引用先前定义的变量。 The % in not mandatory. %不是必须的。 Its just that you will get a format that is decided by the compiler at compile time.
只是您将获得由编译器在编译时确定的格式。 Bit uyou may want to change the output format sometimes.
您有时可能想更改输出格式。
So if i take an example , 因此,如果我举一个例子,
var start = "Monday";
var end = "Friday";
val age = 33
var palindrome = "Dot saw I was Tod";
println(f"date >= $start and date <= $end and age<= $age%f" + palindrome);
I could omit the %f and i will see a output of 33 as it will inferred as Int. 我可以省略%f,我将看到33的输出,因为它将推断为Int。 However i could use %f if i wanted to format it as a float.
但是,如果我想将其格式化为浮点数,可以使用%f。 Also if you use a incompatible formatted you will receive a error at compile time.
另外,如果您使用格式不兼容的格式,则在编译时会收到错误消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.