Home > Enterprise >  How can I get python to loop through multiple suffixes and remove them if present?
How can I get python to loop through multiple suffixes and remove them if present?

Time:08-31

I need to remove "ed", "ly", and/or "ing" from any given phrase... originally i defined suff with all 3 as a tuple but it was only removing the first suffix listed. So i've tried another method as shown below but I know I'm not correct. New to python so any help would be appreciated.

#initalize test list
test_list = ['Running the boy gladly jumped']
 
# printing original list
print("The original list : "   str(test_list))
 
# initialize suffixes
suff = 'ed'
suff1 = 'ly'
suff2 = 'ing'
 
# Suffix removal from String list
# using loop   remove()   endswith()
for word in test_list[:]:
    if word.endswith(suff):
        test_list.word[:-len(suff)]
    elif word.endswith(suff1):
        test_list.word[:-len(suff1)]
    elif word.endswith(suff2):
        test_list.text[:-len(suff2)]
 
# printing result
print("List after removal of suffix elements : "  str(test_list))```

CodePudding user response:

This expression:

    if word.endswith(suff):
        test_list.word[:-len(suff)]

doesn't do anything -- test_list.word isn't valid because word isn't an attribute of test_list, and simply slicing a string doesn't modify it (strings are immutable).

A version of this loop that would do what you intend might be:

for i, word in enumerate(test_list):
    if word.endswith(suff):
        test_list[i] = word[:-len(suff)]
    elif word.endswith(suff1):
        test_list[i] = word[:-len(suff1)]
    elif word.endswith(suff2):
        test_list[i] = word[:-len(suff2)]

enumerate gives us the index i of each word in test_list, and we can use that index to assign a new string to that position in the list. (Be careful when modifying a list in a loop -- in this case it's okay because we aren't changing the length of the list.)

A simpler solution (one that makes it easy to add new suffixes, and to apply this operation in different situations) might be to put your suffixes in a list:

suffixes = ['ed', 'ly', 'ing']

define a function that removes the first encountered suffix from a list of suffixes from a word:

def remove_suffix(word, suffixes):
    for suff in suffixes:
        if word.endswith(suff):
            return word[:-len(suff)]
    return word

and then use that function to redefine your list:

test_list = [remove_suffix(word, suffixes) for word in test_list]

CodePudding user response:

you can try like this

test_list= ['Running the boy gladly jumped']
test_list = list(map(lambda x: x.replace('ing','').replace('ly','').replace('ed',''),test_list))
print(test_list)

output

['Runn the boy glad jump']

CodePudding user response:

Easy to understand solution:

test_list = ['Running the boy gladly jumped']

test_words = test_list[0].split()

suffix_list = ['ed', 'ly', 'ing']

final_list = []

for word in test_words:
    if suffix_list[0] == word[-len(suffix_list[0]):]:
        final_list.append(word[0:-len(suffix_list[0])])
        
    elif suffix_list[1] == word[-len(suffix_list[1]):]:
        final_list.append(word[0:-len(suffix_list[1])])
        
    elif suffix_list[2] == word[-len(suffix_list[2]):]:
        final_list.append(word[0:-len(suffix_list[2])])
    
    else:
        final_list.append(word)
        
final_list = [' '.join(final_list)]
            
print (final_list)

Output

['Runn the boy glad jump']
  • Related