Replace behaving strange?

Initialize string array

s = SubString{String}["Julia", "uses", "multiple", "dispatch", "as", "a", "paradigm,", "making", "it", "easy", "to", "express", "many", "object-oriented", "and", "functional", "programming", "patterns.", "The", "standard", "library", "provides", "..."]

I try to replace a certain character in all strings of the array

replace.(data, "." => "")

yields an error

ERROR: DimensionMismatch("arrays could not be broadcast to a common size")
Stacktrace:
 [1] _bcs1 at .\broadcast.jl:439 [inlined]
 [2] _bcs at .\broadcast.jl:433 [inlined]
 [3] broadcast_shape at .\broadcast.jl:427 [inlined]
 [4] combine_axes at .\broadcast.jl:422 [inlined]
 [5] instantiate at .\broadcast.jl:266 [inlined]
 [6] materialize(::Base.Broadcast.Broadcasted{Base.Broadcast.DefaultArrayStyle{1},Nothing,typeof(replace),Tuple{Array{SubString{String},1},Array{String,1}}}) at .\broadcast.jl:748
 [7] top-level scope at none:0

but

(t->replace(t, "a"=>"x")).(s)

works as expected:

23-element Array{String,1}:
 "Julix"
 "uses"
 "multiple"
 "dispxtch"
 "xs"
 "x"
 "pxrxdigm,"
 "mxking"
 "it"
 "exsy"
 "to"
 "express"
 "mxny"
 "object-oriented"
 "xnd"
 "functionxl"
 "progrxmming"
 "pxtterns."
 "The"
 "stxndxrd"
 "librxry"
 "provides"
 "..."

I expected it to automatically broadcast it over the array. Why doesn’t it work like that?

You need to do replace.(s, ("." => "",)) The Pair is not interpreted as a scalar w.r.t broadcasting.

3 Likes

thanks!

It probably should be?

3 Likes

I can prepare PR if there is support for broadcasting Pair as a scalar.

2 Likes

I’m a nobody in terms of development, but as a new user who found the lack of broadcasting to be confusing, I support it!

Especially since the following works without needing to make the Pair into a tuple:

@. replace(["test", "test2"], r"[es]" => "")

1 Like

https://github.com/JuliaLang/julia/pull/32209

3 Likes