python - 如何在python中识别列表的任何字符串是否包含数字

标签 python

我想确定列表中的任何字符串是否在任何位置包含数字/数字,如果是,则代码应使用 python 从字符串中删除该数字。我的代码是

pattern = '\w+-\w+[-\w+]*|-';
pattern2 = '\d'
contents = ["babies","walked","boys","walking", "CD28", "IL-2", "honour"];
for token in contents:
    if token.endswith("ies"):
        f.write(string.replace(token,'ies','y',1))
    elif token.endswith('s'):
        f.write(token[0:-1])
    elif token.endswith("ed"):
        f.write(token[0:-2])
    elif token.endswith("ing"):
        f.write(token[0:-3])
    elif re.match(pattern,token):
        f.write(string.replace(token,'-',""))
    elif re.match(pattern2,token):
        f.write(token.translate(None,"0123456789"))
    else:
       f.write(t)
f.close()

实际上问题出在re.match(patter2,token)。它不识别 token 中的数字,但 f.write(token.translate(None,"0123456789")) 在我单独使用时效果很好。

最佳答案

您可以在列表理解中使用 re.sub :

>>> contents = ["IL-2", "CD-28","IL2","25"]
>>> import re
>>> [re.sub(r'\d','',i) for i in contents]
['IL-', 'CD-', 'IL', '']

但作为此类任务的更好解决方案,您可以使用 str.translate 方法!

>>> from string import digits
>>> [i.translate(None,digits) for i in contents]
['IL-', 'CD-', 'IL', '']

如果你在 python 3 中:

>>> trans_table = dict.fromkeys(map(ord,digits), None)
>>> [i.translate(trans_table) for i in contents]
['IL-', 'CD-', 'IL', '']

关于python - 如何在python中识别列表的任何字符串是否包含数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29388759/

相关文章:

python - 如何使用数据框中的值更好地构造 SQL 语句?

python - Pandas : csv to dictionary

python - 从输出日志文件中排除 ANSI 转义序列

python - 如何将数据框列转置为 Pandas 中的行

python - 无法使用 PyPDF2 从 PDF 文件中获取文本

Python 列表切片效率

python - 模块 'cv2.cv2' 没有属性 'ximgproc'

python - Tkinter 网格不工作

Python CApi 引用计数详细信息

python - 通过平均多个单元格来简化矩阵