Faster 'if char in string' test

Peter Otten __peter__ at
Thu Jun 24 09:31:54 CEST 2004

Kamilche wrote:

>  was looking for a way to speed up detecting invalid characters in my
> TCP string, and thought of yet another use for the translate function!
> If you were to 'translate out' the bad characters, and compare string
> lengths afterwards, you would know whether or not the line contained
> invalid characters. The new method is more than 10x faster than the
> standard 'if char in string' test! So - here's the code plus sample
> timings:
For a fair comparison you should use a dictionary instead of a string for
the containment test.


More information about the Python-list mailing list