Open In App

Remove character in a String except Alphabet

Last Updated : 24 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a string consisting of alphabets and other characters, remove all the characters other than alphabets and print the string so formed.

Example

Input: str = "$Gee*k;s..fo, r'Ge^eks?"
Output: GeeksforGeeks

Program to Remove characters in a string except alphabets

Below are the steps and methods by which we can remove all characters other than alphabets using List Comprehension and ord() in Python:

  • Using ord() and range()
  • Using filter() and lambda
  • Using isalpha()

Remove All Characters Other Than Alphabets using ord() and range()

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 that ranges from an inclusive to b exclusive with increment/decrement of a given step. In this example, we are using ord() and range() to remove all characters other than alphabets.

Python3




def removeAll(input):
 
    # Traverse complete string and separate
    # all characters which lies between [a-z] or [A-Z]
    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)]
 
    # join all separated characters
    # and print them together
    return ''.join(sepChars)
 
# Driver program
if __name__ == "__main__":
    input = "$Gee*k;s..fo, r'Ge^eks?"
    print (removeAll(input))


Output

GeeksforGeeks


Python Remove All Characters Using filter() and lamda

In this example, we are using filter() and lambda to remove all characters other than alphabets.

Python3




# code
string = "$Gee*k;s..fo, r'Ge^eks?"
print("".join(filter(lambda x : x.isalpha(),string)))


Output

GeeksforGeeks


Remove Characters Other Than Alphabets Using isalpha()

In this example, we are using isalpha(). Here, we are converting 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.

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))


Output

GeeksforGeeks


Time complexity: O(n), where n is length of string
Auxiliary Space: O(n)



Similar Reads

Check input character is alphabet, digit or special character
All characters whether alphabet, digit or special character have ASCII value. Input character from the user will determine if it's Alphabet, Number or Special character.ASCII value ranges- For capital alphabets 65 - 90For small alphabets 97 - 122For digits 48 - 57 Examples : Input : 8 Output : Digit Input : E Output : Alphabet C/C++ Code // CPP pro
3 min read
Reverse every word of the string except the first and the last character
Given string str consisting of a sentence, the task is to reverse every word of the sentence except the first and last character of the words. Examples: Input: str = "geeks for geeks" Output: gkees for gkees Input: str = "this is a string" Output: this is a snirtg Approach: Break the string into words using strtok(), now for every word take two poi
5 min read
Check if frequency of each character is equal to its position in English Alphabet
Given string str of lowercase alphabets, the task is to check if the frequency of each distinct characters in the string equals to its position in the English Alphabet. If valid, then print "Yes", else print "No". Examples: Input: str = "abbcccdddd" Output: Yes Explanation: Since frequency of each distinct character is equals to its position in Eng
8 min read
Smallest alphabet greater than a given character
Given a list of sorted characters consisting of both Uppercase and Lowercase Alphabets and a particular target value, say K, the task is to find the smallest element in the list that is larger than K. Letters also wrap around. For example, if K = 'z' and letters = ['A', 'r', 'z'], then the answer would be 'A'. Examples: Input : Letters = ["D", "J",
10 min read
Python program to Replace all Characters of a List Except the given character
Given a List. The task is to replace all the characters of the list with N except the given character. Input : test_list = ['G', 'F', 'G', 'I', 'S', 'B', 'E', 'S', 'T'], repl_chr = '*', ret_chr = 'G' Output : ['G', '*', 'G', '*', '*', '*', '*', '*', '*'] Explanation : All characters except G replaced by * Input : test_list = ['G', 'F', 'G', 'B', 'E
4 min read
Python - Replace occurrences by K except first character
Given a String, the task is to write a Python program to replace occurrences by K of character at 1st index, except at 1st index. Examples: Input : test_str = 'geeksforgeeksforgeeks', K = '@' Output : geeksfor@eeksfor@eeks Explanation : All occurrences of g are converted to @ except 0th index. Input : test_str = 'geeksforgeeks', K = '#' Output : ge
5 min read
Remove all outgoing edges except edge with minimum weight
Given a directed graph having n nodes. For each node, delete all the outgoing edges except the outgoing edge with minimum weight. Apply this deletion operation for every node and then print the final graph remaining where each node of the graph has at most one outgoing edge and that too with minimum weight. Note: Here, the graph is stored as Adjace
9 min read
Python | Remove all characters except letters and numbers
Given a string, the task is to remove all the characters except numbers and alphabets. String manipulation is a very important task in a day to day coding and web development. Most of the requests and responses in HTTP queries are in the form of Python strings with sometimes some useless data which we need to remove. Remove all characters except le
4 min read
Check if frequency of character in one string is a factor or multiple of frequency of same character in other string
Given two strings, the task is to check whether the frequencies of a character(for each character) in one string are multiple or a factor in another string. If it is, then output "YES", otherwise output "NO". Examples: Input: s1 = "aabccd", s2 = "bbbaaaacc" Output: YES Frequency of 'a' in s1 and s2 are 2 and 4 respectively, and 2 is a factor of 4 F
6 min read
Count of index pairs (i, j) such that string after deleting ith character is equal to string after deleting jth character
Given a string str of N characters, the task is to calculate the count of valid unordered pairs of (i, j) such that the string after deleting ith character is equal to the string after deleting the jth character. Examples: Input: str = "aabb"Output: 2Explanation: The string after deletion of 1st element is "abb" and the string after deletion of 2nd
6 min read
Practice Tags :
three90RightbarBannerImg