Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

string

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.

like image 412
camarman Avatar asked Jul 03 '26 05:07

camarman


1 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.

like image 178
Tim Biegeleisen Avatar answered Jul 05 '26 19:07

Tim Biegeleisen