1

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! =)

3
  • sounds like a job for regex Commented Jul 31, 2018 at 22:05
  • You're using the list method remove. You want a string method instead Commented Jul 31, 2018 at 22:06
  • 1
    Thanks for the advice good sir! It worked like a charm. Commented Jul 31, 2018 at 22:14

3 Answers 3

3

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'] 
Sign up to request clarification or add additional context in comments.

4 Comments

You're amazing! Thanks a lot! =)
I assumed, incorrectly apparently, that he was looking for a generic solution to removing any number from any string.
@SuperStew Oh I see. It was kind of hard to understand I agree :) Jake Glad I could help
@SuperStew... I am trying to remove 0.01 attached to every name in a list. I should have been more clear. My apologies for any misunderstandings.
2

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.

3 Comments

Thank you so much for your help! This code worked great! =)
Can you please add some explanation to the complicated expression in your print command in the interest of those who are new to re which includes me
Great, appreciated!
0

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.

1 Comment

… I have a list of names with 0.01 attached to each of them. For example: Obama, Barak0.01; Trump, Don0.01; etc. When I tried using the code you suggested it only printed the last name in the list (i.e. Trump, Don). Any idea how I could use this code to remove the 0.01 from everyone in the list? This code worked as you stated. I am just new and could use some pointers. Thanks for you time! =)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.