One silly stripping func to complement the lib - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: General (https://python-forum.io/forum-1.html) +--- Forum: Code sharing (https://python-forum.io/forum-5.html) +--- Thread: One silly stripping func to complement the lib (/thread-30076.html) |
One silly stripping func to complement the lib - voidptr - Oct-03-2020 Another silly function I use often... (I got an extention module with functions not in python lib.) Stripping a bunch of caracters from a string. def strStripAll(s,ss): return ''.join([c for c in s if c not in ss]) s = 'q werty 1234567890' ss1 = strStripAll(s,' ') ss2 = s.replace(' ','') ss3 = strStripAll(s,'') ss4 = strStripAll(s,'97 w') ss5 = s.replace('97 w','') ss6 = s.replace('9','').replace('7','').replace(' ','').replace('w','') #lol RE: One silly stripping func to complement the lib - Larz60+ - Oct-03-2020 can you please explain exactly what is being stripped? This looks like it might be greatly simplified. RE: One silly stripping func to complement the lib - voidptr - Oct-04-2020 (Oct-03-2020, 09:48 PM)Larz60+ Wrote: can you please explain exactly what is being stripped? Well, you can install a debugger and follow the example, it is always a good way to see what happen. But the function is easy to follow. and do ... "Stripping a bunch of characters from a string." def strStripAll(s,ss): return ''.join([c for c in s if c not in ss])is easy to follow ... with all characters in s chose those that are not in ss with that result list rebuild a string, so you effectively remove all caracters in ss from the string s. RE: One silly stripping func to complement the lib - scidam - Oct-04-2020 str.translate is a bit faster...:(scidev) dmitry@linux-mh4h:~/workspace/scipy> python -m timeit "'ajklbdkjsbc'.translate(str.maketrans('','','abc'))" 500000 loops, best of 5: 545 nsec per loop (scidev) dmitry@linux-mh4h:~/workspace/scipy> python -m timeit "''.join([c for c in 'ajklbdkjsbc' if c not in 'abc'])" 500000 loops, best of 5: 572 nsec per loop RE: One silly stripping func to complement the lib - voidptr - Oct-04-2020 Interesting, I should add that maketrans and translate can benefit form some examples in the documentation. :) (Oct-04-2020, 01:14 AM)scidam Wrote: |