Home > Mobile >  remove consecutive substrings from a string without importing any packages
remove consecutive substrings from a string without importing any packages

Time:05-14

I want to remove consecutive "a" substrings and replace them with one "a" from a string without importing any packages. For example, I want to get abbccca from aaabbcccaaaa. Any suggestions? Thanks.

CodePudding user response:

This method will remove a determined repeated char from your string:

def remove_dulicated_char(string, char):
    new_s = ""
    prev = ""
    for c in string:
        if len(new_s) == 0:
            new_s  = c
            prev = c
        if c == prev and c == char:
            continue
        else:
            new_s  = c
            prev = c
    return new_s

print(remove_dulicated_char("aaabbcccaaaa", "a"))

CodePudding user response:

using python regular expressions this will do it. If you don't know about regex. They are extremely powerful for this kind of matching

import re

str = 'aaabbcccaaaa'

print(re.sub('a ', 'a', str))

CodePudding user response:

Whats wrong with using a loop?

oldstring = 'aaabbcccaaaa'
# Initialise the first character as the same as the initial string 
# as this will always be the same.
newstring = oldstring[0]

# Loop through each character starting at the second character
# check if the preceding character is an a, if it isn't add it to 
# the new string. If it is an a then check if the current character
# is an a too. If the current character isn't an a then add it to 
# the new string.
for i in range(1, len(oldstring)):
    if oldstring[i-1] != 'a':
        newstring  = oldstring[i]
    else:
       if oldstring[i] != 'a':
           newstring  = oldstring[i]

print(newstring)

CodePudding user response:

You can use a function that removes double values of a string occurrence recursively until only one occurrence of the repeating string remains:

val = 'aaabbcccaaaaaaaaaaa'

def remove_doubles(v):
    v = v.replace('aa', 'a')
    if 'aa' in v:
        v = remove_doubles(v)
        if 'aa' in v:
            v = remove_doubles(v)
        else: return v
    else: return v

print(remove_doubles(val))

CodePudding user response:

There are many ways to do this. Here's another one:

def remove_duplicates(s, x):
    t = [s[0]]
    for c in s[1:]:
        if c != x or t[-1] != x:
            t.append(c)
    return ''.join(t)

print(remove_duplicates('aaabbcccaaaa', 'a'))
  • Related