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?
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)
You can delete the suffix in the following way:
if name.lower().endswith(suffix.lower()):
name = name[0:-len(suffix)]
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’]
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?
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)
You can delete the suffix in the following way:
if name.lower().endswith(suffix.lower()):
name = name[0:-len(suffix)]
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’]