[erlang-questions] Question re io:format and string handling

Robert Virding rvirding@REDACTED
Fri Oct 17 16:45:03 CEST 2008

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

>From your question I would guess it is the 1st version you want,


2008/10/17 David Cabana <drcabana@REDACTED>

> 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.
> Thanks,
> David
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://www.erlang.org/mailman/listinfo/erlang-questions
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20081017/d54e92c6/attachment.htm>

More information about the erlang-questions mailing list