简体   繁体   English

从字符串中删除非字母字符

[英]Remove nonalphabet characters from a string

I have a string like "lake1!" 我有一个类似"lake1!"的字符串"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!" 例如: "lake1!" should return "lake" with 1 and ! 应该返回1 "lake"! removed. 删除。

You can use a generator expression to filter out all non-ascii letters, the use join to create a string from that. 您可以使用生成器表达式来过滤掉所有非ASCII字母,然后使用join从中创建一个字符串。

>>> 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 或同时包含小写和大写字母,您只需检查字符isalpha

>>> s = "Some123?1Example"
>>> ''.join(i for i in s if i.isalpha())
'SomeExample'
word = 'lake1!'
new_word = ''
for char in word:
    if char.isalpha():
        new_word += char

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM