Skip to main content
 首页 » 编程设计

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

2025年05月04日21kuangbin

我想确定列表中的任何字符串是否在任何位置包含数字/数字,如果是,则代码应使用 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', '']