liuzx
liuzx

Reputation: 31

How to output the text with the format I want

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

Answers (2)

vladsiv
vladsiv

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

mozway
mozway

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:

using a list as intermediate
s = 'aaaabbbbcccc||ddddddd||eee||fff'

l = s.split('||')
','.join(l[:-1])+'||'+l[-1]
functional way
'||'.join(map(lambda x: ','.join(x.split('||')), s.rsplit('||', 1)))
limited replacements (require 2 reads of the string)
s.replace('||', ',', s.count('||')-1)

output: 'aaaabbbbcccc,ddddddd,eee||fff'

Upvotes: 1

Related Questions