dissidia
dissidia

Reputation: 1581

Removing only the numeric without affecting other numbers in the string

I have a list of objects that goes as follows, for example:

['ref_2537_1_obj1', 'ref_8953_1_obj32', 'ref_1120_1_obj', 'ref_8919_1_obj143']

And I wanted to remove the numeric that exists at the end of each item in the list, so that it should be like this:

['ref_2537_1_obj', 'ref_8953_1_obj', 'ref_1120_1_obj', 'ref_8919_1_obj']

However, if I tried using .isdigit, it will remove the other numbers that exists. And if I were to use [:1], [:2] or [:3], it also does not seems to be the ideal case as you can see in my example where there exists between 1-3 digits at the end..

What is the best way to approach it?

Upvotes: 0

Views: 61

Answers (3)

Padraic Cunningham
Padraic Cunningham

Reputation: 180522

Since the format is always the same i.e obj then some digits you can could just rindex on j and slice:

In [5]:   l = ['ref_2537_1_obj1', 'ref_8953_1_obj32', 'ref_1120_1_obj', 'ref_8919_1_obj143']

In [6]: [s[:s.rindex("j")+1] for s in l]
Out[6]: ['ref_2537_1_obj', 'ref_8953_1_obj', 'ref_1120_1_obj', 'ref_8919_1_obj']

If you want to update the original list:

In [7]:   l = ['ref_2537_1_obj1', 'ref_8953_1_obj32', 'ref_1120_1_obj', 'ref_8919_1_obj143']

In [8]:  l[:] = (s[:s.rindex("j")+1] for s in l)

In [9]: l
Out[9]: ['ref_2537_1_obj', 'ref_8953_1_obj', 'ref_1120_1_obj', 'ref_8919_1_obj']

Upvotes: -1

pistache
pistache

Reputation: 6243

No need to use pattern matching (regular expressions) when rstrip is enough (it's faster, simpler and more readable) :

a=['ref_2537_1_obj1', 'ref_8953_1_obj32', 'ref_1120_1_obj', 'ref_8919_1_obj143']
print(i.rstrip("0123456789") for i in a)

Upvotes: 3

Vamsi Prabhala
Vamsi Prabhala

Reputation: 49270

You can use re.sub to substitute the ending digits (if there exist any) with blanks.

import re
a=['ref_2537_1_obj1', 'ref_8953_1_obj32', 'ref_1120_1_obj', 'ref_8919_1_obj143']
print ([re.sub(r'\d*$','',i) for i in a])

Upvotes: 2

Related Questions