Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use string func startsWith to check on a list of strings instead of one?

Tags:

scala

I have a list of names:

val listOfNames = List("john", "melanie", "maya", "jack")

and I have a string name full name:

val fullName = "john legend"

and now I want to use the string func startsWith and check if the full name starts with any of those names in the listOfNames, so how can I check it in one line?

something like

if (fullName.startsWith(listOfNames)) {
   //do something
}

thanks!!

like image 472
JohnBigs Avatar asked Dec 04 '16 15:12

JohnBigs


People also ask

Can we use Startswith in a list?

The startswith method can be passed a string or a tuple of strings. If you have a list , make sure to convert it to a tuple by passing it to the tuple() class. The startswith method will return True if the string starts with any of the strings in the tuple, otherwise False is returned.

How do you check if string ends with one of the strings from a list?

Method #1 : Using filter() + endswith() The combination of the above function can help to perform this particular task. The filter method is used to check for each word and endswith method tests for the suffix logic at target list.

How do you check for multiple Startswith in Python?

To check if a given string starts with any of multiple prefixes , you can use the any(iterable) function that returns True if at least one of the values in the iterable evaluates to True . You can check each prefix against the string by using a generator expression like so: any(s. startswith(x) for x in prefixes) .

How do you check if a string is present in a list?

Python Find String in List using count() We can also use count() function to get the number of occurrences of a string in the list. If its output is 0, then it means that string is not present in the list. l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C'] s = 'A' count = l1.


2 Answers

Here's a concrete implementation that checks for any matches with the list of names:

listOfNames.exists(firstName => fullName.startsWith(firstName))
like image 128
Tim Avatar answered Sep 24 '22 02:09

Tim


Another option:

listOfNames.exists(fullName.startsWith)
like image 23
guilhebl Avatar answered Sep 22 '22 02:09

guilhebl