Python Forum
One silly stripping func to complement the lib
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
One silly stripping func to complement the lib
#1
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.

Cool

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
Reply
#2
can you please explain exactly what is being stripped?
This looks like it might be greatly simplified.
Reply
#3
(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.

Smile
Reply
#4
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
Reply
#5
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
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020