简体   繁体   English

如果 Julia 中提供类似 f 字符串的字符串格式?

[英]If the f-string like string formatting available in Julia?

So I am new to Julia and learned various ways of string formatting.所以我是 Julia 的新手,学习了各种字符串格式化方法。 Mainly from websites similar to this .主要来自类似 网站。

So I use f-strings a lot in Python, not a big fan of.format().所以我在 Python 中经常使用 f-strings,而不是 .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?所以我想知道,既然有人创建了 Formatting.jl Package 来带来 Julia 中的类似功能的 Formatting.jl Package,那么是否有任何正在进行或有用的 package 对 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 .如果有人想知道什么是 f 字符串,请参阅

Yes, it is possible with standard Julia strings:是的,可以使用标准 Julia 字符串:

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

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.如果您想比默认字符串插值更多地控制数字格式,您可以使用 Julia 中的Formatting.jl package,它提供 Python f-string 功能。

There is PyFormattedStrings.jl , which is fast and in my experience replicates the Python behaviour most closely out of all the options.PyFormattedStrings.jl ,它速度很快,根据我的经验,它最接近地复制了所有选项中的 Python 行为。

Package Package Syntax句法
PyFormattedStrings.jl PyFormattedStrings.jl f"result = {do(something):.3g}"
Fmt.jl文件 f"result = {$(do(something)):.3g}"
Formatting.jl格式化.jl fmt("result = {:.3f}", do(something))

Note that Formatting has no g support.请注意,格式化没有g支持。 PyFormattedStrings does not support centering, while Fmt does. PyFormattedStrings 不支持居中,而 Fmt 支持。 Neither supports the Python 3.8 f"{4+4=}" syntax.都不支持 Python 3.8 f"{4+4=}"语法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM