Print command in Julia

Hello,
Should there be a " " sign in Julia to print variables and strings? In C/C++ language, " " sign is not needed to print the contents of a variable.

Thank you.

Can you be a bit more precise? I am not sure why a space (if that is what you refer to with " ") should be necessary.

If you do

a=3
print(a)

it just prints (the value of) a. If you also want a new line starting after that, use println(a).

Your message is quite unclear. Are you looking for ”$(var1)moretext”? That is, you can use parentheses if there is no space after the variable to be printed (or if you need to print something more complex: inside the parentheses, you can put arbitrary code)

Hello,
Thank you so much for your reply.
Why didn’t you use $a? Is it because your print statement doesn’t use the " " sign?

To print a variable we need to use a $ before the variable name.

who said this? where? can you provide more context. That is true when you want to interpolate a variable into a string

1 Like

Well, you are mixing maybe two things. Printing and generating strings.

If you just want to print something print(a) would dispatch on a method that prints the value of the variable a but if you want to generate a string containing (the value of) a, then you have to interpolate it, and that is what the $a does within a string.

So you could do s="$a" and get a string and sure, you can also just call the print function of that string print("$a") afterwards (even without storing that in s).
That is possible but not necessary to print a. And there might be cases where both are different, since "$a" internally calls string(a) (and not print(a)).

edit: So I am not sure where your quote is from, but it is not correct, you can but you do not have to.

2 Likes

Hello,
Please take a look at https://www.amazon.com/Julia-Programming-Beginners-Undergraduate-Computer/dp/303073935X.

Hello,
Thank you so much for your reply.
So, when our variable is of string type, we use $ before the variable name.

Hm, then you misread what I wrote or at least are not precise
If you have a string like

s = "HI!"
print(s)

works as well just fine

But if you want to bring a variable into a string – the so-called interpolation, then you do a $ upfront. That is maybe comparable, but not the same, as the %s fields in C/C++s sprints

An example

a=1 # Int
b=0.987 # Float
c = 1//2 # Rational
s = "We have $a, $b, and $c"

Then the String s looks like "We have 1, 0.987, and 1//2"
So the $ is used $ when constructing a string. Sure this might be a string in the argument of a print

5 Likes

Hi,
Thank you so much.

1 Like