使用回复sub仅在python中长度大于11的字符串中的子字符串上

2024-09-30 16:34:57 发布

您现在位置:Python中文网/ 问答频道 /正文

list_1=["TP","MP","TS"]

list_2=["RTS:Id The package is delivered to TEMPR13TS0002",
        "RTS:Id The package is delivered to TEMPS19TS0332"]

我试图在列表2元素的子字符串中查找列表1的元素,并按如下方式替换它们:

对于TS, 输出应为

list_2=["RTS:Id The package is delivered to TEMPR13 TS",
        "RTS:Id The package is delivered to TEMPS19 TS"]

在TS的左边插入空格并删除右边的任何内容。你知道吗

相反,我得到的输出是:

list_2=["R TS:Id The package is delivered to TEMPR13 TS",
        "R TS:Id The package is delivered to TEMPS19 TS"] 

我面临的问题,因为它也会做同样的事情,为RTS子串。我只想执行操作的子串长度大于10。你知道吗

我的列表+正则表达式如下:

  updated_list=[ re.sub(r'(' +  '|'.join(list_1) + ')\S+', 
                 r' \1', i)for i in list_2]

Tags: thetoid元素package列表islist
2条回答

正则表达式不适合检查字符串长度。你知道吗

您可以改变list_1来处理RTS:Id13TS00之间的差异,或者使用其他Python函数来搜索、检查和替换字符串。你知道吗

仅当TS后面跟一个数字时匹配 list_1=["TP","MP","TS\d"]

不是很有效的解决方案:

import re
str = "RTS:Id The package is delivered to TEMPR13TS0002"
pattern = re.compile('\w{11,}')
print pattern.sub(lambda m:re.sub("TS.*", " TS", m.group(0)), str)

相关问题 更多 >