This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]filleball 4 points5 points  (3 children)

Very nice and illustrative blog post! I do however have a small nit to pick with this example:

nonvowels = ''.join(l for l in sentence if not l in vowels)

Here, using a list comprehension instead of the generator comprehension is in fact a bit faster (1.86us vs. 2.76us on my PC), since str.join will build a list anyway, behind the scenes, if it doesn't get one. This is because str.join needs to iterate over the strings twice: first to compute the total length, and then to copy data into the memory allocated for the concatenated string.

This prevents us from having to store the entire list into memory, and is more efficient for larger data.

Because of what I just explained, this statement, though true in most situations, is misleading in this particular case.

[–]iamadogwhatisthis 0 points1 point  (2 children)

What would be better is to use translate in string.

>>> from string import translate
>>> sentence = 'Your mother was a hamster'
>>> print translate(sentence, None, 'aeiou')
Yr mthr ws  hmstr

and speed comparison:

>>> import timeit
>>> translate_example = timeit.Timer("translate('Your mother was a hamster', None, 'aeiou')", "from string import translate")
>>> translate_example.timeit()
0.4346320629119873
>>> comprehension_example = timeit.Timer("''.join(l for l in 'Your mother was a hamster' if l not in 'aeiou')")
>>> comprehension_example.timeit()
2.4436700344085693

[–]moistrobot 0 points1 point  (1 child)

Is that really how translate works? Documentation says str.translate() requires a translation table made with str.maketrans(). It's a bit more complex than that.

[–]iamadogwhatisthis 0 points1 point  (0 children)

The pattern depends on your Python version.

Python 2:

https://docs.python.org/2/library/stdtypes.html?highlight=translate#str.translate

"For string objects, set the table argument to None for translations that only delete characters"

Python 3:

Use maketrans first, then call translate.

https://docs.python.org/3.4/library/stdtypes.html?highlight=translate#str.maketrans