Python Forum
how to remove part of String
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
how to remove part of String
#1
Hi. I have a question on string slicing.
So. I have Series which looks like so:

'one two three'
'four five six'
'five three'
'seven five four six'
'nine one three'
'seven three six'

I must remove the following elements ['three', 'six'] from the rows of Series.

What kind of methods could you advice?
thanks in advance
Reply
#2
Split, filter and join the space-separated strings
import itertools as it

data = [
    'one two three',
    'four five six',
    'five three',
    'seven five four six',
    'nine one three',
    'seven three six',
]

def removed(items, strings):
    items = set(items)
    for s in strings:
        yield ' '.join(it.filterfalse(items.__contains__, s.split(' ')))

if __name__ == '__main__':
    for x in removed(['three', 'six'], data):
        print(repr(x))
Output:
'one two' 'four five' 'five' 'seven five four' 'nine one' 'seven'
Reply


Forum Jump:

User Panel Messages

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