Teknik standar untuk menyaring daftar berlaku, meskipun mereka tidak seefisien split/join
atau translate
metode.
Kami membutuhkan seperangkat ruang putih:
>>> import string
>>> ws = set(string.whitespace)
The filter
builtin:
>>> "".join(filter(lambda c: c not in ws, "strip my spaces"))
'stripmyspaces'
Pemahaman daftar (ya, gunakan kurung: lihat patokan di bawah):
>>> import string
>>> "".join([c for c in "strip my spaces" if c not in ws])
'stripmyspaces'
Lipatan:
>>> import functools
>>> "".join(functools.reduce(lambda acc, c: acc if c in ws else acc+c, "strip my spaces"))
'stripmyspaces'
Benchmark:
>>> from timeit import timeit
>>> timeit('"".join("strip my spaces".split())')
0.17734256500003198
>>> timeit('"strip my spaces".translate(ws_dict)', 'import string; ws_dict = {ord(ws):None for ws in string.whitespace}')
0.457635745999994
>>> timeit('re.sub(r"\s+", "", "strip my spaces")', 'import re')
1.017787621000025
>>> SETUP = 'import string, operator, functools, itertools; ws = set(string.whitespace)'
>>> timeit('"".join([c for c in "strip my spaces" if c not in ws])', SETUP)
0.6484303600000203
>>> timeit('"".join(c for c in "strip my spaces" if c not in ws)', SETUP)
0.950212219999969
>>> timeit('"".join(filter(lambda c: c not in ws, "strip my spaces"))', SETUP)
1.3164566040000523
>>> timeit('"".join(functools.reduce(lambda acc, c: acc if c in ws else acc+c, "strip my spaces"))', SETUP)
1.6947649049999995