I want to remove all spaces from a string.
” as fa sdf sdfsdf “
The result would be:
“asfasdfsdfsdf”
There are several ways I can think of to achieve this, and I’m wondering which one is the best.
1.
"".join(" as fa sdf sdfsdf ".split())
2.
" as fa sdf sdfsdf ".replace(" ", "")
And I assume that there are more.
Which one is preferred?
I believe the best and most efficient method is the second version,
" as fa sdf sdfsdf ".replace(" ", ""), as evidence you can use thetimeitmodule:python -m timeit '"".join(" as fa sdf sdfsdf ".split())'1000000 loops, best of 3: 0.554 usec per looppython -m timeit '" as fa sdf sdfsdf ".replace(" ", "")'1000000 loops, best of 3: 0.405 usec per loop