julia - 如何在 Julia 中将可能是“无”的变量插入字符串?
问题描述
我试图通过将变量的值插入到字符串中来在 Julia 中创建一个动态字符串。直到今天,当值返回nothing
给我留下一个错误时,一切都运行良好。
如何nothing
在字符串中包含 a?至少不必为if n == nothing; n = "None"
我想插入字符串的每个变量经历一些麻烦。
function charge_summary(charges_df)
if size(charges_df)[1] > 0
n_charges = size(charges_df)[1]
total_charges = round(abs(sum(charges_df[:amount])), digits=2)
avg_charges = round(abs(mean(charges_df[:amount])), digits=2)
most_frequent_vender = first(sort(by(charges_df, :transaction_description, nrow), :x1, rev=true))[:transaction_description]
sms_text = """You have $n_charges new transactions, totaling \$$total_charges.
Your average expenditure is \$$avg_charges.
Your most frequented vender is $most_frequent_vender.
"""
return sms_text
else
return nothing
end
end
sms_msg = charge_summary(charges_df)
回报:
ArgumentError: `nothing` should not be printed; use `show`, `repr`, or custom output instead.
string at io.jl:156 [inlined]
charge_summary(::DataFrame) at get-summary.jl:18
top-level scope at none:0
include_string(::Module, ::String, ::String, ::Int64) at eval.jl:30
(::getfield(Atom, Symbol("##105#109")){String,Int64,String})() at eval.jl:91
withpath(::getfield(Atom, Symbol("##105#109")){String,Int64,String}, ::String) at utils.jl:30
withpath at eval.jl:46 [inlined]
#104 at eval.jl:90 [inlined]
hideprompt(::getfield(Atom, Symbol("##104#108")){String,Int64,String}) at repl.jl:76
macro expansion at eval.jl:89 [inlined]
(::getfield(Atom, Symbol("##103#107")))(::Dict{String,Any}) at eval.jl:84
handlemsg(::Dict{String,Any}, ::Dict{String,Any}) at comm.jl:168
(::getfield(Atom, Symbol("##14#17")){Array{Any,1}})() at task.jl:259
解决方案
不幸的是,您必须明确处理nothing
. 例如像这样:
Your most frequented vender is $(something(most_frequent_vender, "None")).
这样做的原因是不清楚您希望如何nothing
转换为字符串,因此您必须提供此值(在您想要的情况下"None"
)。
一个较短的版本是:
Your most frequented vender is $(repr(most_frequent_vender)).
但随后nothing
打印为"nothing"
.
推荐阅读
- machine-learning - 在一个句子中使用 word2vec
- javascript - 在 Windows 10 1809 上的 IE 11 上运行 selenium 测试 - 没有打开新窗口
- java - Docker Compose 链接的微服务不可发现
- python - 使用自定义顺序对熊猫中的列进行排序以获取未知数量的列
- verilog - 关于异步复位如何在复位边缘工作的问题
- excel - 尝试按字符串表号排序
- javascript - 数组未正确索引
- javascript - 有什么方法可以删除 gojs 中的 nodeArrayelements
- r - 有没有办法在 R 中的数据框组内创建索引?
- libssh2 - libssh 与 libssh2 的主要区别是什么?