Formatted string interpolation

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 (GitHub - JuliaString/StringLiterals.jl: Implement improved string literals with Swift-style syntax for interpolation, hex, & unicode characters, plus C & Python style formatting and Unicode, HTML, LaTeX, and Emoji entities) 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?

6 Likes

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"
5 Likes

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.

2 Likes

Try this:

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.

2 Likes

I just submitted a PR to StringLiterals.jl that makes it working under Julia 1+ :slight_smile:

2 Likes

Just saw that someone liked my post. Please read the above-mentioned link. StringLiterals.jl has been superseeded by StrLiterals (+ StrFormat.jl & StrEntities.jl)
But the PR also made it to StrLiterals :slight_smile:

2 Likes