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

Kostis Sagonas kostis@REDACTED
Fri Oct 17 16:43:18 CEST 2008


David Cabana wrote:
> 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. 

This is your lucky day ;-)

Use io_lib:format instead of io:format

Kostis

PS. For better-looking results in the shell, you probably want to
     substitute the ~p with ~s and wrap the io_lib:format call with a
     call to lists:flatten/1 as in:

     lists:flatten(io_lib:format("The ~s in the ~s", ["cat", "hat"])).



More information about the erlang-questions mailing list