Anna Jeanine Anna Jeanine - 1 year ago 146
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!


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

data_trimmed = []
for x in data:


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

Answer Source

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

In [15]:


So you can see that any leading underscores and any in the middle of the string are unaffected, see the docs:

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]

['Anna__67', 'Dyogo_3', 'Kiki_P1', 'BEN_40001']
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download