Automatic separating variables when printing

One (very minor) thing that bothers me in Julia is that print and println do not put spaces between the arguments.

So for example print(1,2,3) prints 123. I wrote my own (probably not ideal) function that does it:

function printlnsep(args...; separator::String = " ")
    println([string(i) * separator for i ∈ args]...)

but I was wondering if there’s something like this in the standard library? And if not, is there a reason why?

Can the separator be a newline character?

Sure, it can be any string… Actually I often use it with separator = "\n"

Would this be OK:

list = 1, 2, 3
print(join(list, ' '))
1 2 3
1 Like

That’s a nicer way to do it! So something like this:

function printlnsep(args...; separator::String = " ")
    println(join(args, separator))

Still I’m wondering why this is not included in Base. Am I the only one who prefers that way of printing?

1 Like

I think I have used both.

When wanting to print a few variables quickly I usually use @show var1 var2 which does this very nicely. And if I want more elaborate printing I don’t mind writing it with join or string interpolation like println("First we have $v1 after which $v2 comes").


No, me too. The default behavior is more general, as removing spaces is harder than adding them. Still, coming from Fortran and having to print numbers all the time, I prefer the Fortran behavior of adding spaces and a new line in the simplest printing command. Something I can live with, though.

Just in case, an additional pair of brackets would fix your example:

(1, 2, 3)

print([1 2 3])
[1 2 3]

I like these solutions a lot. Especially I did not now about string interpolation… :slight_smile:

I agree with @albheim here, it seems like the wrong tool is being used. If you are printing variables just for debug (or any kind of human assessment), then you probably should be using @show instead of println. If you are printing variables in a specific format (possibly to be read back by a program), then you do not want for the function to take any liberties with your input.

1 Like