如何在Erlang中返回格式化字符串



假设您在golang中编码,您可以执行以下操作:

str := fmt.Sprintf("%d is bigger than %d", 6, 4)

二郎怎么样?

Erlang的等价物是

Str = io_lib:format("~p is bigger than ~p", [6, 4])

注意,即使结果在技术上可能不是字符串,通常也不需要通过调用lists:flatten将其转换为字符串。格式化函数的结果通常是iolist的特殊情况。实际上,所有期望字符串的Erlang函数都接受iolists作为参数。

"通常";上面的意思是";如果在格式字符串中不使用Unicode修饰符";。在大多数情况下,不需要使用Unicode修饰符,并且format的结果可以如上所述直接使用。

有一个io_lib:format/2,它完成了这项工作,但请注意,它返回的可能是嵌套的字符列表,而不是字符串。对于一个合适的字符串,您必须在之后flatten/1它:

lists:flatten(io_lib:format("~p is bigger than ~p", [6, 4]))

要将io_lib:format/2与unicode字符一起使用:

50> X = io_lib:format("~s is greater than ~s", [[8364], [36]]). 
** exception error: bad argument
in function  io_lib:format/2
called as io_lib:format("~s is greater than ~s",[[8364],"$"])
51> X = io_lib:format("~ts is greater than ~s", [[8364], [36]]).
[[8364],
32,105,115,32,103,114,101,97,116,101,114,32,116,104,97,110,
32,"$"]
52> io:format("~s~n", [X]).                                     
** exception error: bad argument
in function  io:format/2
called as io:format("~s~n",
[[[8364],
32,105,115,32,103,114,101,97,116,101,114,32,116,
104,97,110,32,"$"]])
*** argument 1: failed to format string
53> io:format("~ts~n", [X]).
€ is greater than $
ok

最新更新