A.D usa
A.D usa

Reputation: 65

Remove special characters from individual python list

I have a list that contain many elements. I was able to find a way to remove duplicates, blank values, and white space.

The only thing left is to:

  1. remove any thing that contain (ae) string.
  2. remove from the list any thing that contain the period (.)

Order of the resulting list is not important. The final list should only contain:

FinalList = ['eth-1/1/0', 'jh-3/0/1', 'eth-5/0/0','jh-5/9/9']

Code:

XYList = ['eth-1/1/0', 'ae1', 'eth-1/1/0', 'eth-1/1/0', 'ae1', 'jh-3/0/1','jh-5/9/9', 'jh-3/0/1.3321', 'jh-3/0/1.53', 'ae0', '', 'eth-5/0/0', 'ae0', '', 'eth-5/0/0', 'ae0', 'eth-5/0/0', '', 'jh-2.1.2']
XYUnique = set(XYList)
XYNoBlanks = (filter(None,XY))
RemovedWhitespace = [item.strip() for item in XYNoBlanks]
# the order of the list is not important
# the final result should be

FinalList = ['eth-1/1/0', 'jh-3/0/1', 'eth-5/0/0','jh-5/9/9']

Upvotes: 2

Views: 358

Answers (2)

Dan
Dan

Reputation: 1884

filtered_l = [s for s in XYList if 'ae' not in s and '.' not in s]

Upvotes: 0

pppery
pppery

Reputation: 3804

The entire conversion sequence (excluding uniqueness) can be accomplished with a list comprehension:

FinalList = [elem.strip() for elem in set(XYList) if elem and "." not in elem and "ae" not in elem]

Upvotes: 1

Related Questions