str.startswith with a list of strings to test for
str.startswith
allows you to supply a tuple of strings to test for:
if link.lower().startswith(("js", "catalog", "script", "katalog")):
From the docs:
str.startswith(prefix[, start[, end]])
Return
True
if string starts with theprefix
, otherwise returnFalse
.prefix
can also be a tuple of prefixes to look for.
Below is a demonstration:
>>> "abcde".startswith(("xyz", "abc"))
True
>>> prefixes = ["xyz", "abc"]
>>> "abcde".startswith(tuple(prefixes)) # You must use a tuple though
True
>>>
How to check if a string starts with one of several prefixes?
Do you mean this:
if (newStr4.startsWith("Mon") || newStr4.startsWith("Tues") || ...)
Or you could use regular expression:
if (newStr4.matches("(Mon|Tues|Wed|Thurs|Fri).*"))
Python String.startswith() with a list of strings in Javascript
All you need is a simple loop over an Array with one of the answers shown there,
var testvar = ['he', 'hi', 'no', 'ye'];
function startsWith2(haystack, needles) {
var i = needles.length;
while (i-- > 0)
if (haystack.lastIndexOf(needles[i], 0) === 0)
return true;
return false;
}
startsWith2('hello world', testvar); // true
startsWith2('foo bar baz', testvar); // false
Similarly for endsWith
;
function endsWith2(haystack, needles) {
var i = needles.length, j, k = haystack.length;
while (i-- > 0) {
j = k - needles[i].length;
if (j >= 0 && haystack.indexOf(needles[i], j) === j)
return true;
}
return false;
}
Check if a string starts with any of the strings in an array
You can use a combination of Array.prototype.some
and String.prototype.startsWith
, both of which are ES6 features:
const substrs = ['the', 'an', 'I'];
function checkIfStringStartsWith(str, substrs) {
return substrs.some(substr => str.startsWith(substr));
}
console.log(checkIfStringStartsWith('the car', substrs)); // true
console.log(checkIfStringStartsWith('a car', substrs)); // false
console.log(checkIfStringStartsWith('i am a car', substrs)); // false
console.log(checkIfStringStartsWith('I am a car', substrs)); // true
How does str.startswith really work?
There is technically no reason to accept other sequence types, no. The source code roughly does this:
if isinstance(prefix, tuple):
for substring in prefix:
if not isinstance(substring, str):
raise TypeError(...)
return tailmatch(...)
elif not isinstance(prefix, str):
raise TypeError(...)
return tailmatch(...)
(where tailmatch(...)
does the actual matching work).
So yes, any iterable would do for that for
loop. But, all the other string test APIs (as well as isinstance()
and issubclass()
) that take multiple values also only accept tuples, and this tells you as a user of the API that it is safe to assume that the value won't be mutated. You can't mutate a tuple but the method could in theory mutate the list.
Also note that you usually test for a fixed number of prefixes or suffixes or classes (in the case of isinstance()
and issubclass()
); the implementation is not suited for a large number of elements. A tuple implies that you have a limited number of elements, while lists can be arbitrarily large.
Next, if any iterable or sequence type would be acceptable, then that would include strings; a single string is also a sequence. Should then a single string argument be treated as separate characters, or as a single prefix?
So in other words, it's a limitation to self-document that the sequence won't be mutated, is consistent with other APIs, it carries an implication of a limited number of items to test against, and removes ambiguity as to how a single string argument should be treated.
Note that this was brought up before on the Python Ideas list; see this thread; Guido van Rossum's main argument there is that you either special case for single strings or for only accepting a tuple. He picked the latter and doesn't see a need to change this.
How to find the python list item that start with
You have several options, but most obvious are:
Using list comprehension with a condition:
result = [i for i in some_list if i.startswith('GFS01_')]
Using filter
(which returns iterator)
result = filter(lambda x: x.startswith('GFS01_'), some_list)
Go StartsWith(str string)
The strings package has what you are looking for. Specifically the HasPrefix function: http://golang.org/pkg/strings/#HasPrefix
Example:
fmt.Println(strings.HasPrefix("my string", "prefix")) // false
fmt.Println(strings.HasPrefix("my string", "my")) // true
That package is full of a lot of different string helper functions you should check out.
Finding whether a string starts with one of a list's variable-length prefixes
A bit hard to read, but this works:
name=name[len(filter(name.startswith,prefixes+[''])[0]):]
how to use string func startsWith to check on a list of strings instead of one?
Here's a concrete implementation that checks for any matches with the list of names:
listOfNames.exists(firstName => fullName.startsWith(firstName))
Related Topics
How to Select Literal Values in an SQLalchemy Query
How to Access the Type Arguments of Typing.Generic
Python List Comprehension - Want to Avoid Repeated Evaluation
Run Code After Flask Application Has Started
Writing to a File in a for Loop Only Writes the Last Value
Find Out How Many Times a Regex Matches in a String in Python
How to Do Row-To-Column Transposition of Data in CSV Table
Python Regular Expression Pattern * Is Not Working as Expected
Installing MySQL Python on MAC Os X
Replace Invalid Values with None in Pandas Dataframe
Scikit-Learn Gridsearchcv with Multiple Repetitions
In Tensorflow, Differencebetween Session.Run() and Tensor.Eval()
How to Install Python Packages in Google's Colab
Numpy to Tfrecords: Is There a More Simple Way to Handle Batch Inputs from Tfrecords