Tutorialspoint
Problem
Solution
Submissions

Remove All Non-Alphabetic Characters from a String

Certification: Basic Level Accuracy: 67.24% Submissions: 58 Points: 5

Write a Python program that removes all non-alphabetic characters from a given string, leaving only letters.

Example 1
  • Input: string = "Hello, World! 123"
  • Output: "HelloWorld"
  • Explanation:
    • Step 1: Iterate through each character in the string.
    • Step 2: Keep only alphabetical characters (a-z, A-Z).
    • Step 3: Remove all other characters (punctuation, numbers, spaces).
    • Step 4: Return the resulting string with only letters.
Example 2
  • Input: string = "Python3.9_is@awesome"
  • Output: "Pythonisawesome"
  • Explanation:
    • Step 1: Iterate through each character in the string.
    • Step 2: Keep only alphabetical characters (a-z, A-Z).
    • Step 3: Remove all other characters (numbers, dots, underscores, at symbols).
    • Step 4: Return the resulting string with only letters.
Constraints
  • 0 ≤ len(string) ≤ 10^6
  • String may contain any printable ASCII characters
  • Time Complexity: O(n) where n is the length of the input string
  • Space Complexity: O(n) for storing the result
StringsControl StructuresFunctions / MethodsWiproAdobe
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use string methods: ''.join(char for char in s if char.isalpha())
  • Use regular expressions: re.sub(r'[^a-zA-Z]', '', s)
  • Filter characters using a loop and check if each character is alphabetic

Steps to solve by this approach:

 Step 1: Initialize an empty string to store the result.

 Step 2: Iterate through each character in the input string.
 Step 3: Check if the current character is alphabetic using isalpha() method.
 Step 4: If the character is alphabetic, add it to the result string.
 Step 5: Skip non-alphabetic characters (punctuation, numbers, spaces).
 Step 6: Return the final string containing only alphabetic characters.

Submitted Code :