Broadcasting string $variable

Is it possible to do something like this:

."X$(1:3)"

and get

@_ "X$_".(1:3)            = ["X1","X2","X3"]

That is, can a vector variable within a string (via $) create a vector of strings. One for each element.

This is the closest I can get.

julia> "X" .* string.(1:3)
3-element Vector{String}:
 "X1"
 "X2"
 "X3"

julia> ["X$x" for x in 1:3]
3-element Vector{String}:
 "X1"
 "X2"
 "X3"
4 Likes

You can try my KeywordStrings :slight_smile: GitHub - adienes/KeywordStrings.jl: Flexible and convenient string formatting for the Julia language

I made this just last weekend exactly for this and similar purposes

kw"X$ix" .% [(;ix) for ix ∈ 1:3]
4 Likes

The closest is

julia> map(i->"X$i", 1:3)
3-element Vector{String}:
 "X1"
 "X2"
 "X3"

If you don’t need the $, you can use:

julia> string.("x", 1:3)
3-element Vector{String}:
 "x1"
 "x2"
 "x3"

julia> string.("x", 1:3, "y")
3-element Vector{String}:
 "x1y"
 "x2y"
 "x3y"
2 Likes

Thanks everyone. this is probably my favourite string.("X", 1:3)

1 Like

This looks close:

(i->"X$i").(1:3)
2 Likes

Note that "X$i" is merely syntax sugar which lowers to string("X", i).

2 Likes

Linking similar thread.

1 Like

What if conversion of "X$i" to string("X", i ) happened before applying the @. macro.

Then you could write @."X$i"

Currently this doesn’t work. I guess the @. macro is applied first and not finding any functions, the statement reduces to “X$i”

1 Like
'x' .* Char.(48 .+ (1:3))
names(DataFrame(zeros(3)', :auto))

:stuck_out_tongue:

1 Like
'x' .* ('0' .+ (1:3))

(Or just 'x' .* ('1':'3'))

1 Like

this should close the search :grinning:.
If the cost function of the expression was the number of pixels :smile:, that would be even better than what the OP asked for.

."X$(1:3)"