Mr.Someone5352
Mr.Someone5352

Reputation: 130

How do I remove part of a string in python list?

I have this output of code (used keyboard module):

[KeyboardEvent(enter up), KeyboardEvent(h down), KeyboardEvent(h up), KeyboardEvent(e down), KeyboardEvent(e up), KeyboardEvent(y down), KeyboardEvent(y up)]

How can I remove every 'KeyboardEvent' from this list?

Upvotes: 3

Views: 4217

Answers (5)

whackamadoodle3000
whackamadoodle3000

Reputation: 6748

Or you could try this which actually removes the KeyBoard event as a string:

a=[KeyboardEvent(enter up), KeyboardEvent(h down), KeyboardEvent(h up), KeyboardEvent(e down), KeyboardEvent(e up), KeyboardEvent(y down), KeyboardEvent(y up)]
a=[str(elem).strip('KeyboardEvent') for elem in a]

Upvotes: 1

Nick
Nick

Reputation: 1008

I would try regular expressions

import re

Foo = [KeyboardEvent(enter up), KeyboardEvent(h down), KeyboardEvent(h up), KeyboardEvent(e down), KeyboardEvent(e up), KeyboardEvent(y down), KeyboardEvent(y up)]

strList = []

for item in Foo:
  bar = re.sub('KeyboardEvent(\(.*?)', '', str(item))
  bar = re.sub('\)', '', bar)
  strList.append(bar)

print strList

Upvotes: 3

Vinícius Figueiredo
Vinícius Figueiredo

Reputation: 6518

How about using KeyboardEvent.name:

newList = [event.name for event in myList]

To get an even better result you can combine this with KeyboardEvent.event_type:

newList = [event.name + ' ' + event.event_type for event in myList]

Demo:

>>> myList
[KeyboardEvent(enter up), KeyboardEvent(h down), KeyboardEvent(h up), KeyboardEvent(e down), KeyboardEvent(e up), KeyboardEvent(y down)]

>>> [event.name for event in myList]
['enter', 'h', 'h', 'e', 'e', 'y']

>>> [event.name + ' ' + event.event_type for event in myList]
['enter up', 'h down', 'h up', 'e down', 'e up', 'y down']

Upvotes: 6

whackamadoodle3000
whackamadoodle3000

Reputation: 6748

a=[KeyboardEvent(enter up), KeyboardEvent(h down), KeyboardEvent(h up), KeyboardEvent(e down), KeyboardEvent(e up), KeyboardEvent(y down), KeyboardEvent(y up)]
a=[elem for elem in a if not isinstance(a, KeyboardEvent)]

This list comprehesion should work

Upvotes: 3

Oqhax
Oqhax

Reputation: 417

Try to remove this using a loop:

list = [KeyboardEvent(enter up), KeyboardEvent(h down), KeyboardEvent(h up), KeyboardEvent(e down), KeyboardEvent(e up), KeyboardEvent(y down), KeyboardEvent(y up)]

for x in list:
    del list[str(x)]

Upvotes: 1

Related Questions