python - 使用正则表达式仅打印字符串中的字母

标签 python python-3.x

目标:我只想在字符串中打印字母

#Input 
#======
string = '   529Wind3@.     '

#Neededoutput
#============
'Wind'

我尝试使用下面的代码对此进行编码

import re
string=re.sub('[^a-z]+[^A-Z]',' ',string)
print(string)

我得到的输出是

ind

但是这段代码只适用于小写 你能告诉我如何编写大写和小写的代码吗

最佳答案

尝试使用列表理解来检查每个字符是否在 string.ascii_letters 中,如果是,它将被存储:

import string
String = '   529Wind3@.     '
print(''.join([i for i in String if i in string.ascii_letters]))

输出:

Wind

关于python - 使用正则表达式仅打印字符串中的字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50695819/

相关文章:

python - 如何在Python中获得列表中数字的总和?

python - 为什么 pandas 的应用比 dataframe 合并慢得多

python - ValueError : Failed to find data adapter that can handle input: <class 'numpy.ndarray' >, <class 'scipy.sparse.csr.csr_matrix'

python - 在 Python 的多处理库中获取队列的长度

python - 有没有办法修复将浮点值附加到 Python 中的字典?

python - 向 MySQL 添加信息不起作用

javascript - 使用 selenium 和 beautifulsoup 进行网页抓取时,通过 id、class、xpath、css 选择器查找元素不会返回任何内容

python - 使用 opencv 识别球时遇到问题

python - 测试字典的所有值是否相等 - 当值未知时

python - 如何找到使用 Turtle Python Graphics 绘制的圆的半径?