0

I have a string like "lake1!" and I want to remove non nonalphabet characters from this string.

How can I do that? Also, this is just an example but in general if have some string how can I remove nonalphabet characters from it?

For example: "lake1!" should return "lake" with 1 and ! removed.

2 Answers 2

3

You can use a generator expression to filter out all non-ascii letters, the use join to create a string from that.

>>> from string import ascii_lowercase >>> s = "lake1!" >>> ''.join(i for i in s if i in ascii_lowercase) 'lake' 

Or to include both lowercase and uppercase letters you can just check if the character isalpha

>>> s = "Some123?1Example" >>> ''.join(i for i in s if i.isalpha()) 'SomeExample' 
Sign up to request clarification or add additional context in comments.

1 Comment

FYI, there is a islower test method too; could use that the same way you use isalpha to simplify. Can even be shortened further to ''.join(filter(str.islower, s)) (in Py2, the ''.join isn't even needed, since filter will return a str directly, simplifying further to filter(str.islower, s)).
0
word = 'lake1!' new_word = '' for char in word: if char.isalpha(): new_word += char 

1 Comment

While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.