Removing suffixes from list Python

Question:

I have 2 lists
where

name = ['Annie A3', 'apple.com', 'John PLG', 'Piggy Alpha CLa'] 
suffixes = ['A3','.Com','pLG','Cla']

I am trying to remove the suffixes from the name list.
What is the best approach in this scenario?

Do i convert both list string into upper/lower case letter and iterate through a for loop to substring?

Asked By: Jackal

||

Answers:

in my opinion, two loops.

names = ['Annie A3', 'apple.com', 'John PLG', 'Piggy Alpha CLa']
suffixes = ['A3','.Com','pLG','Cla']
new_names = []
for name in names:
  for suffix in suffixes:
    if name.lower().endswith(suffix.lower()):
      name = # Do what you want with the suffix
  new_names.append(name)
Answered By: NadavS

You can delete the suffix in the following way:

if name.lower().endswith(suffix.lower()):
    name = name[0:-len(suffix)]
Answered By: Gabio

List comprehension approach. This will just remove all the suffixes and maintain the case of the names as it is in the final output.

names = ['Annie A3', 'apple.com', 'John PLG', 'Piggy Alpha CLa'] 
suffixes = ['A3','.Com','pLG','Cla']

[name[:-len(suffix)].rstrip() for suffix in suffixes for name in names if suffix.lower() in name.lower()]

Output will be:
[‘Annie’, ‘apple’, ‘John’, ‘Piggy Alpha’]

Answered By: Sanjog Mehta
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.