Anna Jeanine Anna Jeanine - 13 days ago 5
Python Question

Python: Trimming underscores from end of String

Hi everyone! I am trying to debug someones code and I have found the problem. The program loops through an array of strings and count's certain ends. The problem is that some of these strings end with

_
, so the counting goes wrong. I would like to use regex, but I am not experienced enough. Could someone help me?

I would like to loop through the array and per string check if it ends with
_
('s) and trim all of these
_
off to put them again in the array!

Update

Thanks for the
rstrip
suggestion! I have tried to write a code that works with my data, but no luck yet...

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

print(data_trimmed)


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

Answer

You can use rstrip('_') to remove trailing underscores:

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

Out[15]:
'__as_das'

So you can see that any leading underscores and any in the middle of the string are unaffected, see the docs: https://docs.python.org/2/library/string.html#string-functions

To answer your updated question you can use a list comprehension to update each string in the list:

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']
Comments