mt1022
mt1022

Reputation: 17299

String interpolation with a function

I wonder why string interpolation in julia works for functions like f1, but failed for findall in the following example. Is there a way for me to use functions like findall with string interpolation?

f1 = function(x, y) x + y end
"1 + 4 = $(f1(1, 4))"

findall(r"a", "abca")

"x: $(findall(r\"a\", \"abca\"))"  # failed

enter image description here

I am using Julia 1.6.1.

Upvotes: 1

Views: 858

Answers (2)

fredrikekre
fredrikekre

Reputation: 10984

In string interpolation inside $(...) you can write regular Julia code, there is no need to escape " etc as in your original example. Just plug in the exact same expression:

julia> findall(r"a", "abca")
2-element Vector{UnitRange{Int64}}:
 1:1
 4:4

julia> "x: $(findall(r"a", "abca"))"
"x: UnitRange{Int64}[1:1, 4:4]"

Upvotes: 2

mt1022
mt1022

Reputation: 17299

This seems work after some trials. But I still do not why it fails with double quotes.

"""x: $(findall(r"a", "abca"))"""

enter image description here

Upvotes: 0

Related Questions