Home > database >  Limit test phrase to a few characters
Limit test phrase to a few characters

Time:08-31

Im having an issue limiting characters not words running different solutions as shown below..any help is appreciated!

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)

CodePudding user response:

If you mean to include only the first 8 characters of each word, you can do this with a list comprehension over final_list like so:

final_list = [word[:min(len(word), 8)] for word in final_list

CodePudding user response:

Removes suffixes and limits each result word to limit characters

limit = 8
test_list = ['Running the boy gladly jumped continuously']
test_words = test_list[0].split()
suffix_list = ['ed', 'ly', 'ing']
final_list = []

for word in test_words:
    for suffix in suffix_list:
        if word.endswith(suffix):
            final_list.append(word[:-len(suffix)][:limit])
            break
    else:
        final_list.append(word[:limit])

print(' '.join(final_list))

Prints:

Runn the boy glad jump continuo

CodePudding user response:

You could use splicing to get the first 8 words

final_list = [' '.join(final_list)][:8]
  • Related