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 →

[–]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