How to return a formatted string in Erlang?

Viewed 123

Assume you're coding in golang, you can do something like:

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

How about Erlang?

3 Answers

The Erlang equivalent would be

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

Note that, even if the result may be not technically a string, normally there is no need to convert it to the string by calling lists:flatten. The result of the format function usually is a special case of iolist. Virtually all Erlang functions expecting a string accept iolists as arguments as well.

"Usually" above means "if Unicode modifier is not used in the format string". In most cases there is no need to use Unicode modifiers, and the result of format can be used directly as described above.

There is io_lib:format/2, that does the job, but note that it returns a possibly nested list of chars, not a string. For a proper string, you have to flatten/1 it afterwards:

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

To use io_lib:format/2 with unicode characters:

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
Related