
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Extract only characters from given string in Python
A piece of data may contain letters, numbers as well as special characters. If we are interested in extracting only the letters form this string of data, then we can use various options available in python.
With isalpha
The isalpha function will check if the given character is an alphabet or not. We will use this inside a for loop which will fetch each character from the given string and check if it is an alphabet. The join method will capture only the valid characters into the result.
Example
stringA = "Qwer34^&t%y" # Given string print("Given string : ", stringA) # Find characters res = "" for i in stringA: if i.isalpha(): res = "".join([res, i]) # Result print("Result: ", res)
Output
Running the above code gives us the following result −
Given string : Qwer34^&t%y Result: Qwerty
With Regular expression
We can leverage the regular expression module and use the function findall giving the parameter value which represents only the characters.
Example
import re stringA = "Qwer34^&t%y" # Given string print("Given string : ", stringA) # Find characters res = "".join(re.findall("[a-zA-Z]+", stringA)) # Result print("Result: ", res)
Output
Running the above code gives us the following result −
Given string : Qwer34^&t%y Result: Qwerty
- Related Articles
- Python program to extract characters in given range from a string list
- How to extract characters from a string in R?
- Python – Extract Percentages from String
- Program to remove duplicate characters from a given string in Python
- How to extract first two characters from a string in R?
- Python Program to Extract Strings with at least given number of characters from other list
- Convert given string so that it holds only distinct characters in C++
- How to extract initial, last, or middle characters from a string in R?
- Python – Extract String elements from Mixed Matrix
- How to extract the first n characters from a string using Java?
- How to extract the last n characters from a string using Java?
- How to extract numbers from a string in Python?
- How to extract date from a string in Python?
- How to check if a string only contains certain characters in Python?
- Extract decimal numbers from a string in Python \n\n

Advertisements