How to use `display` in `sprint`?

Hi all :slight_smile:

I want to do something like that to get the display string.

julia> display_str = sprint(display, Dict(1:10 .=> 1:10))

But it does not work. How would I do that?

julia> _io = IOBuffer()

julia> show(_io, "text/plain", Dict(1:10 .=> 1:10))

julia> String(take!(_io))
"Dict{Int64, Int64} with 10 entries:\n  5 => 5\n  4 => 4\n  6 => 6\n  7 => 7\n  2 => 2\n  10 => 10\n  9 => 9\n  8 => 8\n  3 => 3\n  1 => 1"
1 Like

You could shorten this to sprint(show, "text/plain", Dict(1:10 .=> 1:10)) to eliminate the explicit IOBuffer(), but it is even easier to use repr:

julia> repr("text/plain", Dict(1:10 .=> 1:10))
"Dict{Int64, Int64} with 10 entries:\n  5 => 5\n  4 => 4\n  6 => 6\n  7 => 7\n  2 => 2\n  10 => 10\n  9 => 9\n  8 => 8\n  3 => 3\n  1 => 1"
2 Likes

Realize, by the way, that display doesn’t necessarily print a string at all β€” for example, it might show an image representation of the object in an environment like Jupyter or Pluto. The whole point of display is that it allows the backend to pick which representation of the object to display.

The default display(x) used in the REPL correponds to the three-argument show(stdout, "text/plain", x) representation. So what you really want is the text/plain representation, hence our answers above.

The manual section on Custom Pretty Printing is required reading on this topic, along with the section on Multimedia I/O.

3 Likes

Cool thank you very much. That was really helpful!