如何在Python中从字符串中取出前两位数字

时间:2018-09-19 04:33:34

标签: python

我有2个字符串:

"SP-1-15::PROVPEC=NTK555EA,CTYPE=\"SP-2\",PEC=NTK555EA,REL= 1  ,CLEI=,SER=NNTM,MDAT=UNKNOWN,AGE=00-005-20-03,ONSC=00-005-19-50:IS-ANR,FLT"
"SP-1-16::PROVPEC=NTK555FA,CTYPE=\"SP-2 Dual CPU\",PEC=NTK555FA,REL= 1  ,CLEI=,SER=NNTM,MDAT=UNKNOWN,AGE=UNKNOWN,ONSC=UNKNOWN:IS-ANR,FLT"

我想要两件事:

  1. 如果字符串中的WRK15中删除16(SP-1-15 and SP-1-16)

  2. 如果WRK不在字符串中,请删除在这种情况下为15的奇数值。

1 个答案:

答案 0 :(得分:0)

这可以通过re.searchre.sub来满足我使用WRK来找到.join()的条件来找到s = ["SP-1-15::PROVPEC=NTK555EA,CTYPE=\"SP-2\",PEC=NTK555EA,REL= 1 ,CLEI=,SER=NNTM,MDAT=UNKNOWN,AGE=00-005-20-03,ONSC=00-005-19-50:IS-ANR,FLT", "SP-1-16::PROVPEC=NTK555FA,CTYPE=\"SP-2 Dual CPU\",PEC=NTK555FA,REL= 1 ,CLEI=,SER=NNTM,MDAT=UNKNOWN,AGE=UNKNOWN,ONSC=UNKNOWN:IS-ANR,FLT" ] import re j = ''.join(s) find_sp = re.compile(r'\d+::', re.I) for idx, item in enumerate(s): if 'WRK' in j: s[idx] = re.sub(r'\d+::', '::', item) elif 'WRK' not in j: num = find_sp.search(item) x = num.group(0).strip('::') if int(x) % 2: s[idx] = re.sub(r'\d+::', '::', item) else: pass print(s)

['SP-1-::PROVPEC=NTK555EA,CTYPE="SP-2",PEC=NTK555EA,REL= 1  
,CLEI=,SER=NNTM,MDAT=UNKNOWN,AGE=00-005-20-03,ONSC=00-005-19-50:IS-
ANR,FLT', 'SP-1-16::PROVPEC=NTK555FA,CTYPE="SP-2 Dual   
CPU",PEC=NTK555FA,REL= 1  
,CLEI=,SER=NNTM,MDAT=UNKNOWN,AGE=UNKNOWN,ONSC=UNKNOWN:IS-ANR,FLT']
WRK

,其中一行中有(xenial)vash@localhost:~/python/stack_overflow$ python3.7 strings.py ['SP-1-::PROVPEC=WRKNTK555EA,CTYPE="SP-2",PEC=NTK555EA,REL= 1 ,CLEI=,SER=NNTM,MDAT=UNKNOWN,AGE=00-005-20-03,ONSC=00-005-19-50:IS- ANR,FLT', 'SP-1-::PROVPEC=NTK555FA,CTYPE="SP-2 Dual CPU",PEC=NTK555FA,REL= 1 ,CLEI=,SER=NNTM,MDAT=UNKNOWN,AGE=UNKNOWN,ONSC=UNKNOWN:IS-ANR,FLT']

if