Printf
Printf 模块提供了类似于 C 标准库 printf 的格式化输出函数。它允许将格式化的内容打印到输出流或字符串中。
Printf.@printf — Macro@printf([io::IO], "%Fmt", args...)使用 C printf 风格的格式说明字符串打印 args。可选地,可以将 IO 作为第一个参数传递以重定向输出。
示例
julia> @printf "Hello %s" "world"
Hello world
julia> @printf "Scientific notation %e" 1.234
Scientific notation 1.234000e+00
julia> @printf "Scientific notation three digits %.3e" 1.23456
Scientific notation three digits 1.235e+00
julia> @printf "Decimal two digits %.2f" 1.23456
Decimal two digits 1.23
julia> @printf "Padded to length 5 %5i" 123
Padded to length 5 123
julia> @printf "Padded with zeros to length 6 %06i" 123
Padded with zeros to length 6 000123
julia> @printf "Use shorter of decimal or scientific %g %g" 1.23 12300000.0
Use shorter of decimal or scientific 1.23 1.23e+07
julia> @printf "Use dynamic width and precision %*.*f" 10 2 0.12345
Use dynamic width and precision 0.12有关格式的系统说明,请参见 here。另请参见 @sprintf 以获取结果作为 String 而不是打印出来。
注意事项
Inf 和 NaN 在标志 %a、%A、%e、%E、%f、%F、%g 和 %G 中始终打印为 Inf 和 NaN。此外,如果一个浮点数与两个可能的输出字符串的数值相等,则选择离零更远的输出字符串。
示例
julia> @printf("%f %F %f %F", Inf, Inf, NaN, NaN)
Inf Inf NaN NaN
julia> @printf "%.0f %.1f %f" 0.5 0.025 -0.0078125
0 0.0 -0.007812从 Julia 1.8 开始,%s(字符串)和 %c(字符)的宽度是使用 textwidth 计算的,例如,它忽略零宽字符(如组合字符用于变音符号)并将某些“宽”字符(如表情符号)视为宽度 2。
动态宽度说明符如 %*s 和 %0*.*f 需要 Julia 1.10。
Printf.@sprintf — Macro@sprintf("%Fmt", args...)返回 @printf 格式化的输出作为字符串。
示例
julia> @sprintf "this is a %s %15.1f" "test" 34.567
"this is a test 34.6"Printf.Format — TypePrintf.Format(format_str)创建一个与 C printf 兼容的格式对象,可用于格式化值。
输入的 format_str 可以包含任何有效的格式说明符字符和修饰符。
Format 对象可以传递给 Printf.format(f::Format, args...) 以生成格式化字符串,或传递给 Printf.format(io::IO, f::Format, args...) 以直接将格式化字符串打印到 io。
为了方便,可以使用 Printf.format"..." 字符串宏形式在宏扩展时构建 Printf.Format 对象。
Printf.Format 需要 Julia 1.6 或更高版本。
Printf.format — FunctionPrintf.format(f::Printf.Format, args...) => String
Printf.format(io::IO, f::Printf.Format, args...)将提供的 args 应用到 printf 格式对象 f 并返回格式化的字符串(第一个方法),或直接打印到 io 对象(第二个方法)。有关 C printf 支持的更多细节,请参见 @printf。