Formatted string interpolation

#1

I’m currently looking for a package providing format options when interpolating values in a string, like e.g. in python: f'abc {x:.2f} def'. StringLiterals from JuliaString (https://github.com/JuliaString/StringLiterals.jl) does exactly what I need, but it does not work on Julia 1+. I would be very surprised if there is indeed no possibility for formatted interpolation, so probably I just could not find the package to do this. Could you please help and point in the right direction?

1 Like

#2

Does this work for you?

using Printf
@sprintf "abc %.3f def" pi

there is also the more general interpolation with $:

"abc $(format_my_variable(x)) def"
0 Likes

#3

sprintf is definitely not interpolation - just imagine replacing something similar to 'a = {xyz:.4f} | b = {abs(var):05d} | ...' with more variables and longer names. It is very confusing and error-prone to use sprintf here, especially when modifying a line like this: easy to insert a new variable into wrong place, or remove the wrong one. With interpolation it is much much better (and I guess this is one of the main reasons to have interpolation in the first place). Of course, "a = $(@sprintf "%.4f" xyz) | b = $(@sprintf "%05d" abs(var)) | ..." will work, but is so verbose for such a common task.

0 Likes

#4

Try this:

0 Likes

#5

I looked at Formatting.jl, but didn’t find interpolation there. This package looks like sprintf with a slightly different syntax - so one still needs to keep track of the variables order.

0 Likes