Python – Remove characters greater than K


When it is required to remove characters, which are greater than ‘K’, a simple iteration is used along with the ‘ord’ (Unicode representation) method.

Below is a demonstration of the same −

Example

 Live Demo

my_list = ["python", "is", "easy", "to", "learn"]

print("The list is :")
print(my_list)

K = 9
print("The value of K is ")
print(K)

my_result = []

for element in my_list:
   result_string = ''
   for sub in element:

      if (ord(sub) - 97 <= K):
         result_string += sub
   my_result.append(result_string)

print("The resultant list is :")
print(my_result)

Output

The list is :
['python', 'is', 'easy', 'to', 'learn']
The value of K is
9
The resultant list is :
['h', 'i', 'ea', '', 'ea']

Explanation

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

  • The value for K is defined and is displayed on the console.

  • An empty list is defined.

  • The list is iterated over, and an empty string is created.

  • The elements are checked to see if difference between Unicode representation of the element and 97 is less than K.

  • If yes, the element is appended to empty string.

  • Otherwise, this string is appended to the empty list.

  • This is displayed as output on the console.

Updated on: 04-Sep-2021

92 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements