Python: Underscore underlines from end of line

Hello everybody! I am trying to debug someones code and I found a problem. The program iterates over an array of strings and counts specific ends. The problem is that some of these lines end in _, so the count goes wrong. I would like to use regex, but I am not experienced enough. Can someone help me?

I would like to loop through the array and check the string if it ends with _('s), and trim all these _off to put them back into the array!

Update

Thanks for the offer rstrip! I tried to write code that works with my data, but so far failed ...

data_trimmed = []
        for x in data:
            x.rstrip('_')
            data_trimmed.append(x)

        print(data_trimmed)

But it still returns: ['Anna__67_______', 'Dyogo_3__', 'Kiki_P1_', 'BEN_40001__', .... ]

+4
2

rstrip('_') :

In [15]:
'__as_das___'.rstrip('_')

Out[15]:
'__as_das'

, , , . : https://docs.python.org/2/library/string.html#string-functions

, :

In [18]:
a = ['Anna__67_______', 'Dyogo_3__', 'Kiki_P1_', 'BEN_40001__']
a = [x.rstrip('_') for x in a]
a

Out[18]:
['Anna__67', 'Dyogo_3', 'Kiki_P1', 'BEN_40001']
+6

strstr strstr _

s = 'anything__'
s = s.rstrip('_') # s becomes 'anything'

regex ,

import re
s = 'anything__'
s = re.sub('_+$', '', s)  # s becomes 'anything'
+3

Source: https://habr.com/ru/post/1661572/


All Articles