I'm attempting to create a list (or dictionary, unsure which is more appropriate) which will have values I have input. It will only append inputted values if it follows the correct format, which is two numbers separated by ';;' (123;;091, 101;;451, etc), and then splits the two numbers. How can I do this? newlist = [x.split('::') for x in list if x]
is what I've done but the output comes out as [['123', '101'], ['122', '324'], ['090', '089']]
, which is correct in a sense but if I was to input just 123;;
that would have been accepted.
Any help is greatly appreciated.
CodePudding user response:
You can add a check in that list comprehension to replace if x
with if len(x.split('::')) == 2
. This will only include elements which have values on both sides of your delimiter.
CodePudding user response:
To reject e.g. "789;;abc"
, use .findall()
import re
from pprint import pp
s = "789;;abc apple 123;;101 banana 122;;324 cherry 090;;089 date"
two_nums_re = re.compile(r"(\d );;(\d )")
pp(two_nums_re.findall(s), width=16)
That produces:
[('123', '101'),
('122', '324'),
('090', '089')]
You can easily substitute an alternate delimiter if desired.
>>> " ".join(f"{a}::{b}" for a, b in two_nums_re.findall(s))
'123::101 122::324 090::089'