If the f-string like string formatting available in Julia?

Viewed 3559

So I am new to Julia and learned various ways of string formatting. Mainly from websites similar to this.

So I use f-strings a lot in Python, not a big fan of .format(). So I was wondering since someone created Formatting.jl Package to bring .format() like feature in Julia, is there any ongoing or useful package which does same for f-strings? Now I googled a bit about it too but didn't find anything.

What my main issue is that I want to replicate this behaviour:

a = 10
b = 20
print(f'The multiplication is = {a * b}')

In case anyone wondering what are f-strings, refer to this.

3 Answers

Yes, it is possible with standard Julia strings:

x = "World!"
y = 42
greeting = "Hello $x, $(y^2) !" # gives "Hello World!, 1764 !"

See also here:

https://docs.julialang.org/en/v1/manual/strings/#string-interpolation

Edit: The example in the comment above is

j = 10; b = 20
println("The numbers and their square are $j, $b and $(j^2), $(b^2)")

There are multiple packages, of which the least well known but my favourite is PyFormattedStrings.jl.

Compare:

Package Syntax
PyFormattedStrings.jl f"Our yield is {harvest(crop):.3G} kg."
Fmt.jl f"Our yield is {$(harvest(crop)):.3G} kg."
Formatting.jl fmt("Our yield is {:.3f} kg.", harvest(crop))

(Note that Formatting has no g/G support).

PyFormattedStrings.jl uses the printf syntax, so eg aligning right is done with {var:20g}, and not {var:>20g} as in Python. Fmt.jl does use the Python syntax. Neither package supports the f"{4+4=}" syntax of Python 3.8. (Though Julia has @show).

If you want more control over numeric formatting than the default string interpolation, you can use the Formatting.jl package in Julia, which provides Python f-string functionality.

Related