Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The opposite of string.Template in Python

I know template can work like the following:

x = Template("  Coordinates;     $o1;$o2;$o3;\n")
y = x.substitute(o1 = 23, o2 = 108, o3 = 655)

and y will give me:

"  Coordinates;     23;108;655;\n"

I am wondering if there is a way to do the reverse of this? something like my made up unpack:

x = Template("  Coordinates;     $o1;$o2;$o3;\n")
y = "  Coordinates;     23;108;655;\n"
z = x.unpack(y)

and have z return something like:

["23","108","655"]

any ideas? should i be using regular expressions instead?

EDIT: If using regular expressions how would i program for the following 3 lines to return the first number and the 6 trailing numbers?

   a = "   123;  Coord   ;  19.1335;   3.5010;  1; 3; 8; 4"
   b = "    17;  Coord   ;  15.2940;  13.5010;  3; 1; 8; 8"
   c = "     5;  Coord   ;  19.1345;   0.6200;  1; 1; 7; 8"

I tried this on those and couldn't seem to get it working:

>>> re.match('(\d+);  Coord   ;(\d+);(\d+);(\d+);(\d+);(\d+);(\d+)',a).groups()

SOLUTION: Using regular expressions tutorial (thanks ironchefpython):

>>> import re
>>> text = """
       123;  Coord   ;  19.1335;   3.5010;  1; 3; 8; 4
        17;  Coord   ;  15.2940;  13.5010;  3; 1; 8; 8
         5;  Coord   ;  19.1345;   0.6200;  1; 1; 7; 8
    """
>>> coord = re.compile("\D*(\d+)\D+([\d\.]+)\D+([\d\.]+)\D+(\d+)\D+(\d+)\D+(\d+)\D+(\d+)")
>>> coord.findall(text)
[('123','19.1335','3.5010','1','3','8','4'),('17','15.2940','13.5010','3','1','8','8'),('5','19.1345','0.6200','1','1','7','8')]
like image 270
Symon Avatar asked Jul 09 '26 11:07

Symon


1 Answers

>>> import re
>>> y="  Coordinates;     23;108;655;\n"
>>> re.match("  Coordinates;     (\d+);(\d+);(\d+);\n", y).groups()
('23', '108', '655')

You can also do this to get a dict of the values

>>> re.match("  Coordinates;     (?P<o1>\d+);(?P<o2>\d+);(?P<o3>\d+);\n", y).groupdict()
{'o3': '655', 'o2': '108', 'o1': '23'}
like image 113
John La Rooy Avatar answered Jul 12 '26 02:07

John La Rooy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!