简体   繁体   English

Python字符串替代

[英]Python string substitute

I have the following bit of code that returns some json. 我有以下代码返回一些json。 I want to change the output to be .sub.example.com. 我想将输出更改为.sub.example.com。 Normally I would be able to do this in awk, but in this particular case it needs to be handled in python. 通常我可以在awk中执行此操作,但是在这种情况下,需要在python中进行处理。

What I've been trying to do is replace the literal string 'example.com' but 'sub.example.com'. 我一直想做的是替换文字字符串'example.com'而不是'sub.example.com'。 The filtering out IP bit works, but I just can't figure out what should be the easier part :(. 过滤掉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"
  ]

filterSub() should call re.sub() and return the result. filterSub()应该调用re.sub()并返回结果。 You also need to escape . 您还需要逃脱. in the regular expression, since it has special meaning. 在正则表达式中,因为它具有特殊含义。 And use the $ anchor so you only match it at the end of the domain name. 并使用$定位符,以便仅在域名末尾匹配它。

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

There's no reason to use regex for this: it's a simple string replace. 没有理由为此使用正则表达式:这是一个简单的字符串替换。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM