Home > Blockchain >  Remove empty string in list in Julia
Remove empty string in list in Julia

Time:11-08

I am looking for efficient solution to remove empty string in a list in Julia.

Here is my list :

li = ["one", "two", "three", " ", "four", "five"]

I can remove empty string by using for loop, as following :

new_li = []
for i in li
    if i == " "
    else
        push!(new_li, i)
    end
end

But I believe there is more efficient way to remove the empty string.

CodePudding user response:

new_li = filter((i) -> i != " ", l)

or

new_li = [i for i in l if i != " "]

CodePudding user response:

I have a couple of comments a bit too long for the comments field:

Firstly, when building an array, never start it like this:

new_li = []

It creates a Vector{Any}, which can harm performance. If you want to initialize a vector of strings, it is better to write

new_li = String[]

Secondly, " " is not an empty string! Look here:

jl> isempty(" ")
false

It is a non-empty string that contains a space. An empty string would be "", no space. If you're actually trying to remove empty strings you could do

filter(!isempty, li)

or, for in-place operation, you can use filter!:

filter!(!isempty, li)

But you're not actually removing empty strings, but strings consisting of one (or more?) spaces, and maybe also actually empty strings? In that case you could use isspace along with all. This will remove all strings that are only spaces, including empty strings:

jl> li = ["one", "", "two", "three", " ", "four", "   ", "five"];

jl> filter(s->!all(isspace, s), li)
5-element Vector{String}:
 "one"
 "two"
 "three"
 "four"
 "five"
  • Related