Removing string elements based on the number of the another string element in python

Viewed 56

Let us suppose we have given a string in this form.

xstr = 'hewBllo'

Where each B represents how many previous characters will be deleted from the string. For instance, the above string contains 1 B. Thus, the first letter previous to B will be deleted from the string. The new string should look like this.

new_xstr = 'hello'

Another example:

xstr = 'remoBBBising'

after the transformation, the new string should look like this,

new_xstr = 'rising'

Since there are 3 B letters starting from the first B previous three letters should be deleted from the string. I have come up with an algorithm, but it takes too long for such a seemingly small process. Can you guys think of 1-2 lines of code that can do this process or maybe an intelligent way to do it?

My algorithm:

1-Read the script from behind.

2-When you first encountered B, start counting.

3-When you reach end of B stop counting.

4-Delete the strings as the count.

5-Delete all B letters.

4 Answers

Using a regex replacement with a lambda callback we can try:

str = 'remoBBBising'
output = re.sub(r'(\w+?)(B+)', lambda m: m.group(1)[:-len(m.group(2))] , str)
print(output)  # rising

The logic here is to capture, in two separate groups, both the B term along with the preceding word leading up to it. Then, we replace with just the first captured word, trimming it from the end by the length of the B term.

Try this:

while (s.find('B') != -1):
    i = s.index('B')
    s = s[0:i-1] + s[i+1:]

It's pretty simple and regex is more sophisticated, but it does the job.

You can make a function like this one which is using simple built in string methods to find the amount of B's and the first occurence of B. Then you can return the expected result by slicing the word based on the index and occurences.

def del_pre_B(word):
    bs  = word.count('B')
    i   = word.index('B')
    return word[:i-bs] + word[i+bs:]

Try it:

print(del_pre_B('remoBBBising'))

Output:

rising

You could do this by removing each target character and its preceding character and repeating until the string is exhausted:

def remove_by_char(string, target='B'):
    try:
        i = string.index(target)
    except ValueError:
        return string
    else:
        string = string[:max(0, i-1)] + string[i+1:]
        return remove_by_char(string, target)

or as a while loop:

while target in string:
    i = string.index(target)
    string = string[:max(0, i-1] + string[i+1:]
Related