Reputation: 31
I have meet a problem that I want to delete the duplicates or use other signs to replace them except the last time by Python . For example:
Before: aaaabbbbcccc||ddddddd||eee||fff
After: aaaabbbbccccdddddddeee||fff
OR
aaaabbbbcccc,ddddddd,eee||fff
Upvotes: 0
Views: 44
Reputation: 2946
Using regex:
import re
x = "aaaabbbbcccc||ddddddd||eee||fff"
x = re.sub(r"\|\|(?=[^\|]*\|\|)", ",", x)
print(x)
Result:
aaaabbbbcccc,ddddddd,eee||fff
Use empty string to get the first example:
x = re.sub(r"\|\|(?=[^\|]*\|\|)", "", x)
>>>
aaaabbbbccccdddddddeee||fff
Upvotes: 1
Reputation: 261850
There are many ways to achieve this. The ground principle is to separate the last item and handle it individually.
Here are a few possibilities that do not require imports:
s = 'aaaabbbbcccc||ddddddd||eee||fff'
l = s.split('||')
','.join(l[:-1])+'||'+l[-1]
'||'.join(map(lambda x: ','.join(x.split('||')), s.rsplit('||', 1)))
s.replace('||', ',', s.count('||')-1)
output: 'aaaabbbbcccc,ddddddd,eee||fff'
Upvotes: 1