如何在 erlang 中格式化包含整数的平面字符串?
在erlang中,我想格式化一个包含整数的字符串,并且我希望结果被展平。但我明白了:
io_lib:format("sdfsdf ~B", [12312]).
[115,100,102,115,100,102,32,"12312"]
我可以使用下面的代码获得所需的结果,但它确实不优雅。
lists:flatten(io_lib:format("sdfsdf ~B", [12312])).
"sdfsdf 12312"
是否有更好的格式化字符串,其中包含整数,以便它们是扁平的?理想情况下,只使用一种功能?
In erlang, I want to format a string with integers in it and I want the result to be flattened. But I get this:
io_lib:format("sdfsdf ~B", [12312]).
[115,100,102,115,100,102,32,"12312"]
I can get the desired result by using the code below but it is really not elegant.
lists:flatten(io_lib:format("sdfsdf ~B", [12312])).
"sdfsdf 12312"
Is there a better formatting strings with integers in them, so that they are flat? Ideally, using only one function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如您在示例中所做的那样,您可以使用
lists:flatten/1
展平列表。如果您可以接受二进制文件,
list_to_binary/1
非常有效:但是,首先要问为什么您需要一个平面列表。如果只是化妆品的话就不需要了。
io:format/1,2,3
和大多数其他端口函数(gen_tcp
等)接受所谓的深度 IO 列表(包含字符和二进制文件的嵌套列表):You flatten a list using
lists:flatten/1
as you've done in your example.If you can accept a binary,
list_to_binary/1
is quite efficient:However, question why you need a flat list in the first place. If it is just cosmetics, you don't need it.
io:format/1,2,3
and most other port functions (gen_tcp
etc) accept so called deep IO lists (nested lists with characters and binaries):io_lib:format 返回深度列表有一个效率原因。基本上它节省了对列表的调用:展平。
问问自己为什么希望列表扁平化。如果您要打印列表或将其发送到端口或将其写入文件,所有这些操作都会处理深度列表。
如果出于某种原因你确实需要一个扁平化的列表,那就扁平化它吧。或者,如果您认为重要,您可以创建自己的 my_io_lib:format 来返回扁平列表。
(如果您只想出于调试原因展平列表,则可以使用 ~s 打印字符串,或者在名为
user_default
的 erlang 模块中创建展平器。如下所示:然后您可以使用 fl/1和 Erlang shell 中的 print/1 (当然,只要 user_default.beam 在你的路径中)。
There is an efficiency reason that io_lib:format returns deep lists. Basically it saves a call to lists:flatten.
Ask yourself why you want the list flattened. If you are going to print the list or send it to a port or write it to a file, all those operations handle deep lists.
If you really need a flattened list for some reason, then just flatten it. Or you can create your own my_io_lib:format that returns flattened lists if you think it important.
(If you only want to flatten the list for debugging reasons then either print your strings with ~s, or create a flattener in an erlang module named
user_default
. Something like this:Then you can use fl/1 and print/1 in the Erlang shell (as long as user_default.beam is in your path of course).)