Nielwig
Nielwig

Reputation: 81

How to split a string using any word from a list of word

How to split a string using any word from a list of word

I have a list of string l = ['IV', 'IX', 'XL', 'XC', 'CD', 'CM']

I need to split for example 'XCVI' based on this list like 'XC-V-I'

Upvotes: 1

Views: 54

Answers (1)

Yuan JI
Yuan JI

Reputation: 2995

Here's one solution but I'm not sure if it's the best way to do that:

def split(s, l):
    tokens = []
    i = 0
    while i < len(s):
        if s[i:i+2] in l:
            tokens.append(s[i:i+2])
            i += 2
        else:
            tokens.append(s[i])
            i += 1
    return '-'.join(tokens)

where s is the input string such as "XCVI".

Result:

l = ['IV', 'IX', 'XL', 'XC', 'CD', 'CM']

>>> split('XCVI', l)
XC-V-I
>>> split('IXC', l)
IX-C
>>> split('IXXC', l)
IX-XC

Upvotes: 1

Related Questions