Extract only characters from given string in Python

PythonServer Side ProgrammingProgramming

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

 Live Demo

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

 Live Demo

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
raja
Published on 05-May-2020 10:15:03
Advertisements