Julia: Adding method for `replace!` as `replace!(s::AbstractString, pat=>r; [count::Integer])`

Created on 8 Oct 2020  路  2Comments  路  Source: JuliaLang/julia


I don't know if this is set purposefully, but it seems that we don't have a method for function replace!() when the input argument is an AbstractString? Will this method be added in the future? Thank you!

MWE:

julia> a0= "He is a he."
"He is a he."

julia> replace(a0, "he" =>"she")
"He is a she."

julia> replace!(a0, "he" =>"she")
ERROR: MethodError: no method matching _replace!(::Base.var"#new#267"{Tuple{Pair{String,String}}}, ::String, ::String, ::Int64)
Closest candidates are:
  _replace!(::Union{Function, Type}, ::T, ::T, ::Int64) where T<:Union{AbstractDict, AbstractSet} at set.jl:599
  _replace!(::Union{Function, Type}, ::AbstractArray, ::AbstractArray, ::Int64) at set.jl:635
Stacktrace:
 [1] replace_pairs!(::String, ::String, ::Int64, ::Tuple{Pair{String,String}}) at ./set.jl:467
 [2] replace!(::String, ::Pair{String,String}; count::Int64) at ./set.jl:457
 [3] replace!(::String, ::Pair{String,String}) at ./set.jl:457
 [4] top-level scope at REPL[118]:1

julia> versioninfo()
Julia Version 1.5.2
Commit 539f3ce943 (2020-09-23 23:17 UTC)
Platform Info:
  OS: Linux (x86_64-pc-linux-gnu)
  CPU: Intel(R) Core(TM) i7-1065G7 CPU @ 1.30GHz
  WORD_SIZE: 64
  LIBM: libopenlibm
  LLVM: libLLVM-9.0.1 (ORCJIT, icelake-client)

Although there's a simple workaround:

julia> a0 = "He is a he."
"He is a he."

julia> a0 = replace(a0, "he" =>"she")
"He is a she."

julia> a0
"He is a she."

Most helpful comment

Strings in Julia are immutable, so it's not possible to modify them in-place. This also means no mutating functions can be defined on them.

All 2 comments

Strings in Julia are immutable, so it's not possible to modify them in-place. This also means no mutating functions can be defined on them.

Strings in Julia are immutable, so it's not possible to modify them in-place. This also means no mutating functions can be defined on them.

Cool! Thank you!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

omus picture omus  路  3Comments

manor picture manor  路  3Comments

sbromberger picture sbromberger  路  3Comments

felixrehren picture felixrehren  路  3Comments

tkoolen picture tkoolen  路  3Comments