Reputation: 1460
am trying to ignore a float value from a string and filing to do so.
string = ['20', '30', '40', '.50', '0.60', 'OA', '2A']
code :
match = []
for i in string:
if re.match('(?<![\.\d])[0-9]+(?![\.\d])', i):
match.append(i)
print(match)
output : ['20', '30', '40']
This code is ignoring two elements as they are not numerical 'OA', '2A'
expected output:
['20', '30', '40', 'OA', '2A']
Upvotes: 0
Views: 55
Reputation: 43169
You could use
import re
lst = ['20', '30', '40', '.50', '0.60', 'OA', '2A']
pattern = re.compile(r'-?\d*\.\d+$')
output = [item for item in lst if not pattern.match(item)]
print(output)
This yields
['20', '30', '40', 'OA', '2A']
re.match()
implicitely adds an anchor in the beginning, so the actual pattern is
^-?\d*\.\d+$
As @Wiktor points out, Python 3.x
has re.fullmatch()
, so you could use
pattern = re.compile(r'-?\d*\.\d+')
output = [item for item in lst if not pattern.fullmatch(item)]
Upvotes: 1