Extract all words that begin with x

S

Stefan Behnel

Aahz, 12.05.2010 17:33:
Stefan Behnel said:
superpollo, 11.05.2010 17:03:
Aahz ha scritto:
Have I missed something, or wouldn't this work just as well:

list_of_strings = ['2', 'awes', '3465sdg', 'dbsdf', 'asdgas']
[word for word in list_of_strings if word[0] == 'a']
['awes', 'asdgas']
I would do this for completeness (just in case):

[word for word in list_of_strings if word and word[0] == 'a']
Just guards against empty strings which may or may not be in the list.
... word[0:1] does the same thing. All Python programmers should
learn to use slicing to extract a char from a string that might be
empty.
The method call of .startswith() will be slower, I am sure.

And if it is slower, so what? Using startswith() makes for faster
reading of the code for me, and I'm sure I'm not the only one.

also, what if the OP intended "words that begin with x" with x a string
(as opposed to a single character) ?

word[:len(x)] == x

will work in that case.

But that's now going to be slower. ;-) (Unless one makes the obvious
optimization to hoist len(x) out of the loop.)

Right, I forgot to mention that I left that as an exercise to the reader.

Stefan
 
T

Terry Reedy

also, what if the OP intended "words that begin with x" with x a string
(as opposed to a single character) ?

word[:len(x)] == x

will work in that case.

But that's now going to be slower. ;-) (Unless one makes the obvious
optimization to hoist len(x) out of the loop.)

If x were a known literal, then len(x) could be replaced by the actual
size. But I admit that that is a nuisance and point of failure. I think
comparing start/end strings of variable length or length greater than
one is the real justification for the new methods, not the OP's trivial
single-char case.

Terry Jan Reedy
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,143
Latest member
SterlingLa
Top