Python:只保留字符串中的字母 [英] Python: keep only letters in string

查看:143
本文介绍了Python:只保留字符串中的字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从字符串中删除不在字母表中的所有字符的最佳方法是什么?我的意思是,删除所有空格、标点符号、括号、数字、数学运算符..

例如:

input: 'as32{ vd"s k!+'输出:'asvdsk'

解决方案

你可以使用 re,但你真的不需要.

<预><代码>>>>s = 'as32{ vd"s k!+'>>>''.join(x for x in s if x.isalpha())'asvdsk'>>>filter(str.isalpha, s) # 适用于 python-2.7'asvdsk'>>>''.join(filter(str.isalpha, s)) # 在 python3 中有效'asvdsk'

What is the best way to remove all characters from a string that are not in the alphabet? I mean, remove all spaces, interpunction, brackets, numbers, mathematical operators..

For example:

input: 'as32{ vd"s k!+'
output: 'asvdsk'

解决方案

You could use re, but you don't really need to.

>>> s = 'as32{ vd"s k!+'
>>> ''.join(x for x in s if x.isalpha())
'asvdsk'    
>>> filter(str.isalpha, s) # works in python-2.7
'asvdsk'
>>> ''.join(filter(str.isalpha, s)) # works in python3
'asvdsk'

这篇关于Python:只保留字符串中的字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆