如何在python中搜索组合od dot和forward slash

时间:2017-05-14 16:10:39

标签: python regex

我是Python的初学者,我想用regex替换我的字符串中的一些特定字符。

HR_list = '../frankfurt/', '/CA/en/vancouver', '../../../IT/en/rom/'

如果我的字符串包含'../',我想用DE / en替换它,如果我的字符串包含'../../../',我想用“”替换它。所以我的代码是:

for href in HR_list:
    if (re.findall('\\b\.\.\/\.\.\/\.\.\\b', href)):
        LIST.append("mystring" + (href.replace("../../..", "")))
    elif (re.findall('\\b\.\.\\b', href)):
        LIST.append("mystring" + (href.replace("..", "/DE/en")))
    else:
        LIST.append("mystring" + href)

预期结果应为:

mystring/DE/en/frankfurt, mystring/CA/en/vancouver, mystring/IT/en/rom/

1 个答案:

答案 0 :(得分:2)

如何两次使用replace

HR_list = '../frankfurt/', '/CA/en/vancouver', '../../../IT/en/rom/'

['mystring' + href.replace('../../..', '').replace('..', '/DE/en') for href in HR_list]
# ['mystring/DE/en/frankfurt/', 'mystring/CA/en/vancouver', 'mystring/IT/en/rom/']