Stream: helpdesk (published)

Topic: Appending empty string to `String[]`


view this post on Zulip mbaz (Jun 01 2021 at 02:00):

Is this a bug?

julia> s=String[]
String[]

julia> append!(s,"")
String[]

push! seems to work:

push!(s,"")
1-element Vector{String}:
 ""

view this post on Zulip mbaz (Jun 01 2021 at 02:07):

Nevermind, I figured it out.

julia> append!(String[], [""])
1-element Vector{String}:
 ""

view this post on Zulip Kwaku Oskin (Jun 01 2021 at 03:13):

Guess it's the same thing as in
https://discourse.julialang.org/t/tutorial-efficient-and-safe-approaches-to-mutation-in-data-parallelism/62105/4

Probably append!(String[], ("", )) should work too.

view this post on Zulip Fredrik Ekre (Jun 01 2021 at 05:44):

Are you looking for push!? That is for adding elements whereas append! iterates the argument and adds the elements in the iterator.

view this post on Zulip Gunnar Farnebäck (Jun 01 2021 at 07:09):

The reason why append!(s, "") does nothing is that it iterates over the characters in the string, but there are none so nothing happens. If you have a non-empty string it fails since the element type is wrong:

julia> s = String[]
String[]

julia> append!(s, "abc")
ERROR: MethodError: Cannot `convert` an object of type Char to an object of type String
Closest candidates are:
  convert(::Type{String}, ::String) at essentials.jl:210
  convert(::Type{T}, ::T) where T<:AbstractString at strings/basic.jl:231
  convert(::Type{T}, ::AbstractString) where T<:AbstractString at strings/basic.jl:232
  ...
Stacktrace:
 [1] setindex!(A::Vector{String}, x::Char, i1::Int64)
   @ Base ./array.jl:839
 [2] _append!(a::Vector{String}, #unused#::Base.HasLength, iter::String)
   @ Base ./array.jl:991
 [3] append!(a::Vector{String}, iter::String)
   @ Base ./array.jl:981
 [4] top-level scope
   @ REPL[2]:1

Not sure I like that it doesn't clean up the pre-allocation when it errors though:

julia> s
3-element Vector{String}:
 #undef
 #undef
 #undef

view this post on Zulip mbaz (Jun 01 2021 at 13:05):

Thanks to all! I was indeed looking for push!. What happened is that, by mistake, I read append!(String[], "") as "append the empty string to String[]" instead of "append the elements of the empty string to String[]".

I don't work often on strings and I don't automatically think of them as iterators (yet).


Last updated: Dec 28 2024 at 04:38 UTC