Home > Software engineering >  How to remove "g" with regex from this list in python with regex?
How to remove "g" with regex from this list in python with regex?

Time:10-29

I have this list:

list = ['12kg','900g', '2,7kg', '801g', '15', '3,63kg', '1kg]

and I want to remove only letter g (or replace with "") when I have pattern <number>g, which means:

new_list = ['12kg', '900', '2,7kg', '801', '15', '3,63kg', '1kg]

I've tried to write the following but failed they all failed:

  • [^kK]g: for some reason gets last digit (0g and 1g)
  • [^kK]g$: nothing comes up (I expected the sign $ would get the end of string)
  • [^kK](g): it does work but in a group -> How do I replace the group match with what I want?

CodePudding user response:

Is this what you're looking for?

import re


lst = ['12kg', '900g', '2,7kg', '801g', '15', '3,63kg', '1kg']
newLst = [re.sub('([0-9] )g$', lambda x: x.groups()[0], el) for el in lst]
print(newLst)  # => ['12kg', '900', '2,7kg', '801', '15', '3,63kg', '1kg']

The regex I used here was ([0-9] )g$. This will match the string with at least one number and end with "g". The re.sub call will then replace the string with only the number part.

CodePudding user response:

How about:

import re
list = ['12kg','900g', '2,7kg', '801g', '15', '3,63kg', '1kg']
[re.sub('(\d)g', r'\1',x) for x in list]

['12kg', '900', '2,7kg', '801', '15', '3,63kg', '1kg']

This matches a digit followed by g, and substitutes back the digit alone. The trick is \d matches a digit, (\d) puts the matched digit into a group, and \1 substitute group 1, which is the digit without the g.

CodePudding user response:

If you know the "g" is always at the end, you don't need a regex:

new_list = [x[:-1] for x in list]

p.s. Don't use the name list in your own code since there is already a list in the Python builtin package.

  • Related