Python Program to Group Strings by K length Using Suffix



When it is required to group strings by K length using a suffix, a simple iteration and the ‘try’ and ‘except’ blocks are used.

Example

Below is a demonstration of the same

my_list = ['peek', "leak", 'creek', "weak", "good", 'week', "wood", "sneek"] print("The list is :") print(my_list) K = 3 print("The value of K is ") print(K) my_result = {} for element in my_list: suff = element[-K : ] try: my_result[suff].append(element) except: my_result[suff] = [element] print("The resultant list is :") print(my_result)

Output

The list is : ['peek', 'leak', 'creek', 'weak', 'good', 'week', 'wood', 'sneek'] The value of K is 3 The resultant list is : {'ood': ['good', 'wood'], 'eak': ['leak', 'weak'], 'eek': ['peek', 'creek', 'week', 'sneek']}

Explanation

  • A list of strings is defined and is displayed on the console.

  • The value of ‘K’ is defined and is displayed on the console.

  • An empty dictionary is defined.

  • The list is iterated over.

  • The list is reversed and assigned to a variable.

  • The ‘try’ block is used to append the element to the dictionary.

  • The ‘except’ block assigns the element to the list’s specific index.

  • This list is the output that is displayed on the console.

Updated on: 2021-09-20T09:01:30+05:30

257 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements