Reputation: 17
I'm trying to split a string using a multiple character delimiter, I can keep the delimiter in the result, but it is in the first part rather than the second part where I need it. This is what I have.
test = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
d = 'DEF'
for line in test:
s = [e+d for e in test.split(d) if e !=""]
print s
['ABCDEF', 'GHIJKLMNOPQRSTUVWXYZDEF']
What I need is for the DEF at the split to be in part 2. I would appreciate any help.
Upvotes: 0
Views: 2377
Reputation: 15015
Try like this:-
test = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
words= list(word)
first=[]
second=[]
for w in words:
if w ==A or w==B or w==C:
first.append(w)
else:
second.append(w)
head='',join(first)
tail='',join(second)
[head,tail]
Upvotes: 0
Reputation: 180411
just add DEF
to the second element:
s1,s2 = test.split(d)
print [s1,d + s2]
Or add inside the split list:
spl = test.split(d)
spl[-1] = d + spl[-1]
In your own code, you are just reassigning the value of s
each time not adding to it so your loop is pointless:
for line in test:
s = [e+d for e in test.split(d) if e !=""]
Upvotes: 0
Reputation: 369084
Using str.partition
:
>>> test = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> d = 'DEF'
>>> head, sep, tail = test.partition(d)
>>> [head, sep+tail]
['ABC', 'DEFGHIJKLMNOPQRSTUVWXYZ']
Upvotes: 1