How to use `endswith()` against multiple values in Julia?

Viewed 67

I have a string and I want to use endswith() on it but against multiple values.

My first guess was to try it with a tuple:

# {string}

suffixes = ({multiple suffixes here})

endswith(i,extensions)

This generated the error message:

MethodError: no method matching endswith(::String, ::Tuple{String, String})

So, I went looking for official documentation at Julia documentation but they only talk about single string comparions.

I did find this on an unofficial site that says:

If the second argument is a vector or set of characters, tests whether the last character of string belongs to that set.

Which does not quite apply.

I tried the following variations:

endswith(i,extensions[:])

Produces the same error as before MethodError: no method matching endswith(::String, ::Tuple{String, String})

Variations with list:

# {string}

suffixes = [{multiple suffixes here}]

endswith(i,extensions)

Only changes the error message from tuple to vector

MethodError: no method matching endswith(::String, ::Vector{String})

Or with the index supplied

# {string}

suffixes = [{multiple suffixes here}]

endswith(i,extensions[:])

Same error

MethodError: no method matching endswith(::String, ::Vector{String})

I tried endswith(i,extensions[1:length(extensions)]) with both tuples and vectors and that did not work either.

Anyone familiar?

2 Answers

It seems the following is also possible:

endswith("{string}",r"item_one|item-two|item_three|item_four") # items being what I want to check the string for.

And if my items are dynamic I guess I can use an f-string to create the r"{item_list_here}"

You probably want the following:

julia> endswith.("abcd", ["d", "c", "cd", "dc"])
4-element BitVector:
 1
 0
 1
 0

Note the . after endswith. This operation broadcasts the function over the collection (in this case vector of suffixes). For more information see here.

Related