Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to remove all characters except letters in a string in Python?

I call a function that returns code with all kinds of characters ranging from ( to ", and , and numbers.

Is there an elegant way to remove all of these so I end up with nothing but letters?

like image 292
Joan Venge Avatar asked Apr 17 '14 19:04

Joan Venge


People also ask

How do you exclude a letter from a string in Python?

You can remove a character from a Python string using replace() or translate(). Both these methods replace a character or string with a given value. If an empty string is specified, the character or string you select is removed from the string without a replacement.

How do I keep letters only in a string Python?

You can use the regular expression 'r[^a-zA-Z]' to match with non-alphabet characters in the string and replace them with an empty string using the re. sub() function. The resulting string will contain only letters.


1 Answers

Well, I use this for myself in this kind of situations

Sorry, if it's outdated :)

string = "The quick brown fox jumps over the lazy dog!"
alphabet = "abcdefghijklmnopqrstuvwxyz"

def letters_only(source):
    result = ""
    for i in source.lower():
        if i in alphabet:
            result += i
    return result

print(letters_only(string))
like image 198
LiquiD.S1nn3r Avatar answered Oct 12 '22 21:10

LiquiD.S1nn3r