Jake West
Jake West

Reputation: 33

How can I remove a specific number from a string?

here is the code:

aList = ['0.01', 'xyz', 'J0.01', 'abc', 'xyz'];
aList.remove('0.01');
print("List : ", aList)

here is the output: List :

['xyz', 'J0.01', 'abc', 'xyz']

How can I remove the 0.01 attached to 'J0.01'? I would like to keep the J. Thanks for your time! =)

Upvotes: 1

Views: 128

Answers (3)

Andrej Kesely
Andrej Kesely

Reputation: 195593

Using re module:

import re

aList = ['0.01', 'xyz', 'J0.01', 'abc', 'xyz'];    
print([i for i in (re.sub(r'\d+\.?\d*$', '', i) for i in aList) if i])

Prints:

['xyz', 'J', 'abc', 'xyz']

EDIT:

The regexp substitution re.sub(r'\d+\.?\d*$', '', i) will substitute every digit followed by dot (optional) and followed by any number of digits for empty string. The $ signifies that the digit should be at the end of the string.

So. e.g. the following matches are valid: "0.01", "0.", "0". Explanation on external site here.

Upvotes: 2

fabianmedina09
fabianmedina09

Reputation: 1

Something like that can works:

l = ['0.01', 'xyz', 'J0.01', 'abc', 'xyz']
string = '0.01'
result = []
for x in l :
    if string in x:
        substring = x.replace(string,'')
        if substring != "":
            result.append(substring)
    else:
        result.append(x)

print(result)

try it, regards.

Upvotes: 0

rafaelc
rafaelc

Reputation: 59284

Seems like you want

aList = ['0.01', 'xyz', 'J0.01', 'abc', 'xyz'];
>>> [z.replace('0.01', '') for z in aList]

['', 'xyz', 'J', 'abc', 'xyz']

If you want to remove also empty strings/whitespaces,

>>> [z.replace('0.01', '') for z in aList if z.replace('0.01', '').strip()]
['xyz', 'J', 'abc', 'xyz']

Upvotes: 3

Related Questions