[erlang-questions] Question re io:format and string handling
Fri Oct 17 23:55:32 CEST 2008
Robert Virding wrote:
> There is nothing exactly like what Python does. There are options though:
> - You can use io_lib:format which returns a, possibly deep, list of
> characters which is the the representation of format string and the
> arguments. So:
> Phrase = io_lib:format("The ~p in the ~p", ["cat", "hat"])
> Depending on what you are going to do, you may have to apply lists:flatten
> to the string to get a flat list. io_lib:format has the same format options
> as io:format, and is in fact called by io:format to generate the output
> - A more direct but less general way is to concatenate the string directly:
> Cat = "cat",
> Hat = "hat",
> Phrase = "The " ++ Cat ++ " in the " ++ Hat
Another minor variation that avoids repeated appends (++) which may be
useful if the initial texts are large to avoid a costly O(N^2) append
(lists:flatten/1 is O(N log N)):
Cat = "cat",
Hat = "hat",
Phrase = lists:flatten(["The ", Cat, " in the ", Hat])
> >From your question I would guess it is the 1st version you want,
> 2008/10/17 David Cabana <>
>> Consider the result of evaluating the following in an erl console:
>> io:format("The ~p in the ~p", ["cat", "hat"]).
>> The strings "cat" and "hat" are substituted for the occurrences of ~p, and
>> a string is printed to the console.
>> Is there a way to bind that string to a variable instead of printing it to
>> the console?
>> What I am after is a facility somewhat like the one used in the Python
>> example below:
>> phrase = "The %s in the %s" % ("cat", "hat")
>> Evaluating the example above results in the variable 'phrase' taking the
>> value "The cat in the hat".
>> The similarity to the io:format behavior is clear. The Python idiom is
>> useful, and I have been looking for something
>> similar in Erlang, without luck. Before I try to concoct such a thing, I
>> thought I'd ask whether it already exists.
>> erlang-questions mailing list
> erlang-questions mailing list
More information about the erlang-questions