how to identify that anystring of list contains digits or not in python -
i want identify whether string of list contain number/ digit @ position, , if code should remove digit string use of python. code
pattern = '\w+-\w+[-\w+]*|-'; pattern2 = '\d' contents = ["babies","walked","boys","walking", "cd28", "il-2", "honour"]; 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()
actually problem in re.match(patter2,token)
. not identify digit in token f.write(token.translate(none,"0123456789"))
worked when used alone.
you can use re.sub
within list comprehension :
>>> contents = ["il-2", "cd-28","il2","25"] >>> import re >>> [re.sub(r'\d','',i) in contents] ['il-', 'cd-', 'il', '']
but better solution such task can use str.translate
method!
>>> string import digits >>> [i.translate(none,digits) in contents] ['il-', 'cd-', 'il', '']
and if in python 3 :
>>> trans_table = dict.fromkeys(map(ord,digits), none) >>> [i.translate(trans_table) in contents] ['il-', 'cd-', 'il', '']
Comments
Post a Comment