首页 > 解决方案 > 用顺序名称替换字符串?

问题描述

我想做的事情比解释更容易出现。假设我有一个这样的字符串:

The ^APPLE is a ^FRUIT

使用正则表达式 re.sub(),我想得到这个:

The ^V1 is a ^V2

看看它们是如何递增的。但现在更难的情况来了:

The ^X is ^Y but ^X is not ^Z

应该翻译成这样:

The ^V1 is ^V2 but ^V1 is not ^V3

即,如果它重复,那么它会保留替换,即 ^X => ^V1 情况。

我听说替换可以是一个函数,但不能正确。

https://www.hackerrank.com/challenges/re-sub-regex-substitution/problem

标签: pythonregexsubstitution

解决方案


IIUC,你不需要re。字符串操作将完成这项工作:

from collections import defaultdict

def sequential(str_):
    d = defaultdict(int)
    tokens = str_.split()
    for i in tokens:
        if i.startswith('^') and i not in d:
            d[i] = '^V%s' % str(len(d) + 1)
    return ' '.join(d.get(i, i) for i in tokens)

输出:

sequential('The ^APPLE is a ^FRUIT')
# 'The ^V1 is a ^V2'

sequential('The ^X is ^Y but ^X is not ^Z')
# 'The ^V1 is ^V2 but ^V1 is not ^V3'

推荐阅读