How to Compose a Array Comprehension embedding a Condition Test?

I have a code as the following:

list = []
for itr in "Watch out! Hello, world"
    if isletter(itr)
        append!(list,itr)
    end
end
println(list)

How can I convert the above code snippet into an array comprehension? Something like:

[isletter(itr) ? itr : $(give it up) for itr in str]

Maybe you can use a generator expression with the if keyword:
(https://docs.julialang.org/en/v1/manual/arrays/#Generator-Expressions)

str = "Watch out! Hello, world"
[ c for c in str if isletter(c) ]
2 Likes

Thanks, your solution works. Inspired by your work, I found another tech:

filter(isletter, str)
2 Likes

Be aware that this is a bad idea. It will force your output array to have eltype Any. In order to initialize an empty vector of characters write:

list = Char[]

Initializing arrays with a plain [] is a serious performance trap.

2 Likes

Get it! Thanks for your explanations.