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
can you please explain exactly what is being stripped?
This looks like it might be greatly simplified.
(Oct-03-2020, 09:48 PM)Larz60+ Wrote: [ -> ]can you please explain exactly what is being stripped?
This looks like it might be greatly simplified.
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.

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
Interesting,
I should add that maketrans and translate can benefit form some examples in the documentation.
:)
(Oct-04-2020, 01:14 AM)scidam Wrote: [ -> ]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