
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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.
- Related Articles
- Python program to concatenate Strings around K
- Python program to omit K length Rows
- Program to equal two strings of same length by swapping characters in Python
- Program to find smallest value of K for K-Similar Strings in Python
- Python program to remove K length words in String
- Program to merge strings alternately using Python
- Program to find length of longest set of 1s by flipping k bits in Python
- Program to find length of longest sublist containing repeated numbers by k operations in Python
- Python program to Sort Strings by Punctuation count
- Python program to sort strings by substring range
- Python Program to Join strings by multiple delimiters
- Program to find maximum length of k ribbons of same length in Python
- Python Program to get K length groups with given summation
- Python - Group contiguous strings in List
- Program to get maximum length merge of two given strings in Python

Advertisements