0

Say I have the following string

s = "DH3580-Fr1-TRG-TRB-DH1234-Fr3"

and I have a list of characters

l = ['Fr1', 'TRG', 'TRB', 'SOUL']

Excluding the string upstream of the first - (DH3580), I want to scan s until it finds the last element which is present in l, in this case TRB. Finally I want to split the string s by the immediate - thereafter. So that s becomes the list

['DH3580-Fr1-TRG-TRB', 'DH1234-Fr3']

What would be the best way to do this in python3?

There is a very similar question here, although for JavaScript

S.B
  • 13,077
  • 10
  • 22
  • 49
BCArg
  • 2,094
  • 2
  • 19
  • 37

2 Answers2

1

There are many undefined requirements in your question (e.g. would elements in s and l be ordered?), but maybe this solution would work:

def indices(list1, list2):
    idx = []
    for l2 in list2:
        if l2 in list1:
            idx.append(list1.index(l2))
    return idx

s = 'DH3580-Fr1-TRG-TRB-DH1234-Fr3'
l = ['Fr1', 'TRG', 'TRB', 'SOUL']

tokens = s.split('-')
imax = indices(tokens, l)[-1]  # index of the last matching elements

['-'.join(tokens[:imax+1]), '-'.join(tokens[imax+1:])]  # [up to matching, remainder]
# ['DH3580-Fr1-TRG-TRB', 'DH1234-Fr3']
0

You need to first split your text into individual items, then make an iterator out of it. I did this because I need it to be exhausted in order to later get the rest of the text.

l = ["Fr1", "TRG", "TRB", "SOUL"]
s = "DH3580-Fr1-TRG-TRB-DH1234-Fr3"

first, *rest = s.split("-")

rest_iterator = iter(rest)
res = [first]
first_excluded_item = None
for part in rest_iterator:
    if part in l:
        res.append(part)
    else:
        first_excluded_item = part
        break

if first_excluded_item:
    rest = [first_excluded_item, *rest_iterator]
else:
    rest = list(rest_iterator)
print(["-".join(res)] + ["-".join(rest)])

output:

['DH3580-Fr1-TRG-TRB', 'DH1234-Fr3']
S.B
  • 13,077
  • 10
  • 22
  • 49