Python字符串子字符串

2024-07-04 18:06:03 发布

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

下面的代码返回一些json。我想把输出改为。sub.example.com网站. 通常我可以在awk中完成这项工作,但在这种特殊情况下,需要用python处理。在

我一直在尝试替换字符串'example.com网站'但是'sub.example.com网站'. 过滤掉的IP位起作用了,但我不知道什么是更容易的部分:(。在

def filterIP(fullList):
   regexIP = re.compile(r'\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$')
   return filter(lambda i: not regexIP.search(i), fullList)

def filterSub(fullList2):
   regexSub = re.recompile('example.com', 'sub.example.com', fullList2)

groups = {key : filterSub(filterIP(list(set(items)))) for (key, items) in groups.iteritems() }

print(self.json_format_dict(groups, pretty=True))

  "role_1": [
    "type-1.example.com",
    "type-12-sfsdf-453-2.example.com"
  ]

Tags: keyrecomjson网站exampledeftype
2条回答

没有理由为此使用regex:它只是一个简单的字符串替换。在

def filterSub(fullList2):
    return fullList2.replace("example.com", "sub.example.com")

filterSub()应该调用re.sub()并返回结果。您还需要在正则表达式中转义.,因为它有特殊的含义。并使用$锚点,以便只在域名的末尾匹配它。在

def filterSub(fullList2):
    return re.sub(r'example\.com$', 'sub.example.com', fullList2)

相关问题 更多 >

    热门问题