Python :将多次出现的字符替换为一个,但将一次出现的字符替换为 none

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

我有一个字符串:

a = '0202201131181'

我想用单个 1 替换 a 中所有多次出现的 1(如果存在),但如果只找到一次“1”,则将其替换为空字符串 ''.

我的最终目标是:

a = '0202201318'

这里字符'8'后的'1'只出现一次,所以用空字符串代替,但是字符'3'之前和字符后的'11','3'被替换为' 1'.

这是我试过的 if-else 代码块,部分正确:

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

但它输出'02022013181',这是不正确的。如何做到这一点?

正则表达式可能是最好的选择:

import re

a = '020220111311811001001001001'

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

首先分出单个 1,然后分出多次出现的 1。为了测试目的,我在 a 中添加了一些字符,输出为

0202201318100000000

如果您不喜欢单行代码造成的混乱:

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

(?<!1)1(?=[^1]|$)的解释:

  • (?<!1):确保前面的字符不是1
  • 1:字面上匹配一个1
  • (?=[^1]|$):确保前面的字符是 a) 不是 1,或者 b) 是字符串的结尾。

这是一种无需使用正则表达式即可获得预期输出的方法。 我正在做的是,我将字符串从“11”中拆分出来,并将所有“1”替换为空 space,然后再次将列表加入到带有“1”的字符串中。

a = '0202201131181'
tmp =[ i.replace('1', '') for i in a.split('11')]
print(('1').join(tmp))

列表理解的细分:

a = '0202201131181'
tmp =[]

for i in a.split('11'):
  i = i.replace('1','')
  tmp.append(i)

print(('1').join(tmp))

基于正则表达式的解决方案是最好的。没有两个想法。

另一种不使用正则表达式的逻辑,仅作记录:

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))

输出:

02022013181

非正则表达式解决方案,灵感来自@Jay。我对 Python 的了解为零,因此语法可能需要更改。当然,没有测试。 "Benefit": 条件没那么复杂(我希望)。

a = '110202201111311811'
new_str = []

while (not end of string) :
    while ((a[i]!='1') and (not end of string))
        new_str.append(a[i])
        i++

    if (a[i+1] is not out of range ) and (a[i+1] != '1') :
        i++
    else :
        new_str.append(a[i])
        while a[i]=='1' :
            i++

print ("".join(x for x in new_str))
a = '111020220113111111'
while a.find('11') != -1:
  i = 0
  j = 1
  while i < len(a):
    for c in a:
        if a[i] == '1':
            if a[j] == '1':
                a = a.replace(a[i],'x')
    i = i + 1
    j = i + 1
  a = a.replace("xx","1")
  a = a.replace("x","1")
print(a)

我用上面的代码尝试了以下几种情况:

a = '111020220113111111'          >> 1020220131
a = '020220111311811001001001001' >> 02022013181001001001001
a = '0202201131181'               >> 02022013181

注意:编辑了我之前的代码。