How to use show
to pretty print matrix to String?
It's possible to print it to stdout
with show(stdout, "text/plain", rand(3, 3))
.
I'm looking for something like str = show("text/plain", rand(3, 3))
For simple conversions usually DelimitedFiles
is your best friend.
julia> a = rand(2,3);
julia> using DelimitedFiles
julia> writedlm(stdout, a)
0.7609054249392935 0.5417287267974711 0.9044189728674543
0.8042343804934786 0.8206460267786213 0.43575947315522123
If you want to capture the output use a buffer:
julia> b=IOBuffer();
julia> writedlm(b, a)
julia> s = String(take!(b))
"0.7609054249392935\t0.5417287267974711\t0.9044189728674543\n0.8042343804934786\t0.8206460267786213\t0.43575947315522123\n"
Last but not least, if you want to have a stronger control use CSV
- and the pattern is the same - either use stdout
or capture the output using a buffer e.g.:
julia> using CSV, Tables
julia> b=IOBuffer();
julia> CSV.write(b, Tables.table(a));
julia> s = String(take!(b))
"Column1,Column2,Column3\n0.7609054249392935,0.5417287267974711,0.9044189728674543\n0.8042343804934786,0.8206460267786213,0.43575947315522123\n"
Even more - if you want to capture the output from display
- you can too!
julia> b=IOBuffer();
julia> t = TextDisplay(b);
julia> display(t,a);
julia> s = String(take!(b))
"2×3 Array{Float64,2}:\n 0.760905 0.541729 0.904419\n 0.804234 0.820646 0.435759"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With