How to uniformly get part of string elements from array of strings

Suppose that we have the array

z = ["aaa","bbb","ccc"]

and we want to get a new array where each element has only the first two characters

z_target = ["aa","bb","cc"]

I tried

getindex.(z,1:2)

but it thows the error
ERROR: DimensionMismatch(“arrays could not be broadcast to a common size; got a dimension with lengths 3 and 2”)

Any ideas?

getindex.(z,Ref(1:2)) will work — you need to tell it not to broadcast over the 1:2 array.

6 Likes

@Emmanouil_Bakirtzis, what about chop.(z) ?
Or more generally: chop.(z, head=0, tail=1), or better: SubString.(z, 1, 2)

3 Likes

or, more literally,

julia> z = ["aaa","bbb","ccc"]
3-element Array{String,1}:
 "aaa"
 "bbb"
 "ccc"

julia> x = [ s[1:2] for s in z ]
3-element Array{String,1}:
 "aa"
 "bb"
 "cc"

6 Likes

Thanks, works perfect.