24

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 3

20

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)")
Sign up to request clarification or add additional context in comments.

8 Comments

Well this isn't exactly what I was referring to. So I was looking for this kind of functionality: j = 10; b = 20 print(f'The numbers and their square are {j}, {b} and {j2}, {b2}') I hope I am making sense here. Does something like this exist in Julia?
print("The multiply is $(j * b)")
Okay, I understood what I was doing wrong and this is super silly and I can't believe I was making such a mistake. So I was trying to concat two strings using + sign inside the print this way and just now realized- in julia string concatination happens via *. Well, sorry for pestering you so much. The day I learned in Julia that's how you concat strings, I knew one day this would cause some confusion.
No problem - the string concatination is Julia has a rather uncommon sign ;-)
|
7

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).

Comments

2

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.

1 Comment

As of 2023, do not use the Formatting.jl package. It has catastrophic correctness bugs and is unmaintained, see github.com/JuliaIO/Formatting.jl/issues/108

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.