Open In App

Python – Extract only characters from given string

Last Updated : 10 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

To extract only characters (letters) from a given string we can use various easy and efficient methods in Python.

Using str.isalpha() in a Loop

str.isalpha() method checks if a character in a string is an alphabetic letter. Using a loop, we can iterate through each character in a string to filter out or count only the alphabetic characters.

# Input string
s = "abc123!@#XYZ"

# Extract only characters
result = ''.join(char for char in s if char.isalpha())

# Print the result
print(result)

Output
abcXYZ

Explanation

  • The code uses a generator expression within join() to iterate through each character in the string and checks if it is alphabetic using char.isalpha(). Only letters are included in the resulting string.
  • The final string contains only the alphabetic characters from the input, omitting any digits or special characters.

Using Regular Expressions (re.sub)

Using Regular Expressions (re.sub) is an efficient way to process strings by replacing specific patterns. For extracting alphabetic characters, re.sub can remove non-letter characters, providing a streamlined approach for cleaning or filtering text.

import re

# Input string
s = "abc123!@#XYZ"

# Extract only characters using regex
result = re.sub(r'[^a-zA-Z]', '', s)

# Print the result
print(result)

Output
abcXYZ

Explanation

  • The regular expression [^a-zA-Z] matches any character that is not a letter (uppercase or lowercase). The ^ indicates negation, and the range a-zA-Z specifies alphabetic characters.
  • The re.sub function replaces all non-alphabetic characters with an empty string (''), effectively extracting only the letters from the input string.

Using List Comprehension

Using List Comprehension involves iterating over each character in the string and conditionally including only the alphabetic characters in the result.

# Input string
s = "abc123!@#XYZ"

# Extract only characters using list comprehension
result = ''.join([char for char in s if char.isalpha()])

# Print the result
print(result)

Output
abcXYZ

Explanation

  • list comprehension iterates over each character in the input string and checks if it is alphabetic using char.isalpha(). Only alphabetic characters are included in the resulting list.
  • join() method concatenates the filtered characters into a single string, effectively removing non-alphabetic characters from the input string.


Next Article
Practice Tags :

Similar Reads

three90RightbarBannerImg