Disambiguating variable names in string interpolation

I’ve got another newbie question. In Julia it’s possible to interpolate strings into one another, e.g.

julia> greet = "Howdy"
"Howdy"

julia> whom = "cowgirls"
"cowgirls"

julia> "$greet, $whom"
"Howdy, cowgirls"

julia>

However, when adding an exclamation mark after $whom, Julia tries to interpolate the variable whom! instead:


julia> "$greet, $whom!"
ERROR: UndefVarError: whom! not defined
Stacktrace:
 [1] top-level scope
   @ REPL[52]:1

julia>

My question is, how do you avoid that? My first instinct was to use curly braces, i.e.

julia> "$greet, ${whom}!"
ERROR: syntax: invalid interpolation syntax: "${"
Stacktrace:
 [1] top-level scope
   @ none:1

julia>

but as you can see this didn’t work, and neither did escaping the exclamation mark,

julia> "$greet, $whom\!"
ERROR: syntax: invalid escape sequence
Stacktrace:
 [1] top-level scope
   @ none:1

julia>

As always, thanks a lot!

normal parentheses, "$(whom)!"

4 Likes

a more artisanal workaround

"$greet, $whom"*'!' 

Whether it is “more artisanal” is a matter of taste, but using * in this way allocates an extra temporary string, unfortunately.

1 Like