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!!
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.
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.
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) .
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.
Here's a concrete implementation that checks for any matches with the list of names:
listOfNames.exists(firstName => fullName.startsWith(firstName))
Another option:
listOfNames.exists(fullName.startsWith)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With