String Interpolation in Julia and Python

We can combine strings with variables in a number of ways in Julia.

julia> name = "Erik"
julia> age = 41

This is an example of string interpolation.

julia> "Hello, $name. You are $age."
"Hello, Erik. You are 41."

Here is the what the above syntax gets turned into. Sometimes it is more practical to perform string interpolation directly this way.

julia> string("Hello, ", name, ". You are ", age)
"Hello, Erik. You are 41."

This is string concatenation using the * operator. That is somewhat different from other languages which tend to use + for this purpose. However this makes more mathematical sense.

julia> "Hello, " * name * ". You are " * string(age)
"Hello, Erik. You are 41."

With Python we got an even wider variety of choices. You can read about more of the details here.

The modern way of doing this, which is also most similar to Julia, would be to use f-strings:

python> name = "Erik"
python> age = 41
python> f"Hello, {name}. You are {age}."
'Hello, Erik. You are 41.'

There are two alternative old-school ways of doing this in Python.

python> name = "Erik"
python> age = 41
python> "Hello, %s. You are %s." % (name, age)
'Hello, Erik. You are 41.'

However when string get longer, this can get harder to keep track of which is why old school Python offers some alternatives:

"Hello, {1}. You are {0}.".format(age, name)
"Hello, {name}. You are {age}.".format(name = name, age = age)

String concatinations are done with the + operator

"Hello, " + name + ". You are " + str(age)

But you cannot use str() with multiple arguments like Julia's string() function.

Next we’ll look at ranges and slices in Julia and Python.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store