List comprehension and ord() in Python to remove all characters other than alphabets
Given a string consisting of alphabets and other characters, remove all the characters other than alphabets and print the string so formed. Examples:
Input : str = "$Gee*k;s..fo, r'Ge^eks?"
Output : GeeksforGeeks
This problem has existing solution please refer Remove all characters other than alphabets from string link. We will solve this problem in python quickly using List Comprehension.
Approach : is
1. Traverse string
2. Select characters which lie in range of [a-z] or [A-Z]
3. Print them together
How does ord() and range() function works in python ?
- The ord() method returns an integer representing the Unicode code point of the given Unicode character.For example,
ord('5') = 53 and ord('A') = 65 and ord('$') = 36
- The range(a,b,step) function generates a list of elements which ranges from a inclusive to b exclusive with increment/decrement of given step.
Python3
def removeAll( input ):
sepChars = [char for char in input if
ord (char) in range ( ord ( 'a' ), ord ( 'z' ) + 1 , 1 ) or ord (char) in
range ( ord ( 'A' ), ord ( 'Z' ) + 1 , 1 )]
return ''.join(sepChars)
if __name__ = = "__main__":
input = "$Gee * k;s..fo, r'Ge^eks?"
print (removeAll( input ))
|
Output:
GeeksforGeeks
Python3
string = "$Gee*k;s..fo, r'Ge^eks?"
print ("".join( filter ( lambda x : x.isalpha(),string)))
|
Approach#3: Using isalpha()
Convert the input string into a list of characters. Loop through the list of characters. If the current character is not an alphabet, replace it with an empty string. Join the list of characters back into a string. Return the resulting string.
Algorithm
1. Define a function called remove_non_alpha_chars that takes a string as input.
2. Convert the input string into a list of characters.
3. Loop through the list of characters.
4. If the current character is not an alphabet, replace it with an empty string.
5. Join the list of characters back into a string.
6. Return the resulting string.
Python3
def remove_non_alpha_chars(s):
chars = list (s)
for i in range ( len (chars)):
if not chars[i].isalpha():
chars[i] = ''
return ''.join(chars)
s = "$Gee*k;s..fo, r'Ge^eks?"
print (remove_non_alpha_chars(s))
|
Time complexity: O(n), where n is length of string
Auxiliary Space: O(n)