Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python : replace multiple occurrence of characater by one but single occurrence by none

I have a string:

a = '0202201131181'

I want to replace all multiple occurrences of 1 in a if present, by a single 1 but if only one occurrence of '1' is found then replace it by empty string ''.

My end goal is to get:

a = '0202201318'

Here the '1' after character '8' is occurring only once, so it's replaced by empty string, but the '11' before the character '3' and after the character, '3' is replaced by '1'.

Here is an if-else code block I tried, which is partially correct:

if '11' in a:
    a = a.replace("11","1")
else:
    a = a.replace("1","")

But it outputs '02022013181', which is incorrect. How to do this?

like image 581
Arkistarvh Kltzuonstev Avatar asked Dec 13 '22 13:12

Arkistarvh Kltzuonstev


2 Answers

Regex is probably the best option:

import re

a = '020220111311811001001001001'

a = re.sub(r'1{2,}', '1', re.sub(r'(?<!1)1(?=[^1]|$)', '', a))
print(a)

First sub out single 1s, then sub out multiple occurrences of 1. I added some more characters to a for testing purposes, and the output is

0202201318100000000

If you don't like the somewhat confusion caused by the one-liner:

a = re.sub(r'(?<!1)1(?=[^1]|$)', '', a)
a = re.sub(r'1{2,}', '1', a)

Explanation of (?<!1)1(?=[^1]|$):

  • (?<!1): Make sure the character before is not a 1.
  • 1: Literally match a 1.
  • (?=[^1]|$): Make sure the character ahead is either a) not a 1, or b) is the end of the string.
like image 83
iz_ Avatar answered Feb 16 '23 01:02

iz_


Regex based solution is the best. No two thoughts on that.

Just a another logic without using regular expressions, just for the record:

a = '110202201111311811'
new_str = []

for i in range(len(a)):
   if a[i] == '1':
       if (i!= (len(a)-1) and a[i+1] == '1') and (i!=0 and a[i-1] != '1'):
           new_str.append(a[i])
   else:
       new_str.append(a[i])

print ("".join(x for x in new_str))

Output:

02022013181
like image 30
Jay Avatar answered Feb 16 '23 01:02

Jay