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

如何在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.wri

我想确定列表中的任何字符串是否在任何位置包含数字/数字,如果是,那么代码应该使用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.matchpatter2,token。它不能识别令牌中的数字,但f.writetoken.translateNone,0123456789在我单独使用时效果很好

如果要删除数字,请使用:

如果您只想在字符串包含混合物时删除数字:

print([s.translate(None,"0123456789") if not s.isdigit() else s for s in contents])
  ['IL-', 'CD-', 'IL', '25']
如果数字始终在末尾,则可以使用rstrip:

print([s.rstrip("0123456789") for s in contents])
对于python 3,您需要使用以下命令创建一个表:


如果要删除数字,请使用:

如果您只想在字符串包含混合物时删除数字:

print([s.translate(None,"0123456789") if not s.isdigit() else s for s in contents])
  ['IL-', 'CD-', 'IL', '25']
如果数字始终在末尾,则可以使用rstrip:

print([s.rstrip("0123456789") for s in contents])
对于python 3,您需要使用以下命令创建一个表:

您只需在列表中使用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方法作为更好的解决方案

如果您使用的是python 3:

>>> trans_table = dict.fromkeys(map(ord,digits), None)
>>> [i.translate(trans_table) for i in contents]
['IL-', 'CD-', 'IL', '']
您只需在列表中使用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方法作为更好的解决方案

如果您使用的是python 3:

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

@在你回答之前,我一直在编辑我的答案!我也提到了str.translate!我总是提到这类问题@是的,我看到了你的答案,但在我的回答之后,无论如何你也会得到我的投票@在你回答之前,我一直在编辑我的答案!我也提到了str.translate!我总是提到这类问题@是的,我看到了你的答案,但在我的回答之后,无论如何你也会得到我的投票!评论不用于扩展讨论;此对话已结束。评论不用于扩展讨论;这段对话已经结束。