Python – Remove characters greater than K

When working with strings, you may need to filter out characters based on their position in the alphabet. This technique removes characters that appear after a certain position K in the alphabet using the ord() function to get Unicode values.

Understanding the Approach

The method compares each character's alphabetical position with K. Since lowercase 'a' has ASCII value 97, we subtract 97 from each character's ASCII value to get its alphabetical position (a=0, b=1, c=2, etc.).

Example

Here's how to remove characters greater than K from a list of strings ?

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

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

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

result = []

for word in words:
    filtered_string = ''
    for char in word:
        if (ord(char) - 97 <= K):
            filtered_string += char
    result.append(filtered_string)

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

How It Works

The algorithm processes each character by:

  • Converting to position: ord(char) - 97 gives alphabetical position (a=0, b=1, ...)
  • Comparing with K: Only characters at position ? K are kept
  • Building result: Valid characters are concatenated to form the filtered string

Character Position Reference

With K=9, these characters are kept: a(0), b(1), c(2), d(3), e(4), f(5), g(6), h(7), i(8), j(9). Characters like 'p'(15), 'y'(24), 't'(19), 'o'(14), 'n'(13) are removed since they exceed K=9.

Alternative Approach Using List Comprehension

words = ["python", "is", "easy", "to", "learn"]
K = 9

result = [''.join([char for char in word if ord(char) - 97 <= K]) for word in words]
print("Result using list comprehension:", result)
Result using list comprehension: ['h', 'i', 'ea', '', 'ea']

Conclusion

Use ord(char) - 97 to convert characters to alphabetical positions for filtering. This technique is useful for alphabet-based string processing and can be implemented with loops or list comprehensions.

Updated on: 2026-03-26T00:51:24+05:30

242 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements