Having difficulty understanding how to properly convert Perl match to Python

Viewed 109

I have a Perl example that seems exceptionally messy and inefficient when I attempt the same task in Python. Can someone that has better grasp in Python workings comment on how to simplify the python snip to be more similar to the Perl example in simplicity and coding fluff? Both these snips (Perl and Python) produce equivalent results. The key focus is the test then extraction of the regex within the parenthesis. The Python case seems to require the regex to be processed twice.


#Perl Example:
   elsif ($teststring =~ m/^([0-9\.]+)[Xx]$/)
   {
      $ExtractedVa = $1;
   }
#Python Example of how to implement the perl functionality above:
    elif (re.search(r"^([0-9\.]+)[Xx]$",teststring)):  
        parts=re.search(r"^([0-9\.]+)[Xx]$",teststring)
        ExtractedVa=float(parts.group(1)) # Convert from string to numeric
3 Answers

If you are using Python 3.8 or greater,

elif parts := re.search(....., teststring):

If you are not up to 3.8, then you just make it two statements:

else:
    parts = re.search(....., teststring)
    if parts:

but then you have to further indent everything inside the else.

The "walrus" operator := was added to Python for just this sort of thing.

== Edited. ==

I accidentally used := in both the 3.8 code and the <3.8 code. The latter should have been the normal assignment operator '='

Remember the result of the search in a variable:

match = re.search(r"^([0-9\.]+)[Xx]$",teststring)
if match:
    ExtractedVa=float(match.group(1)) # Convert from string to numeric

Posted question does not give enough problem details.

Perhaps something like following code snippet should be a solution.


#!/usr/bin/env python3.7
#
# vim: ai ts=4 sw=4

import re

str = '''
192.168.0.12 server_1 room_1
192.168.0.14 server_2 room_2
192.168.0.16X server_3 room_3
192.168.0.18x server_4 room_4
192.168.0.32 server_5 room_5
'''

m = re.findall(r"^([\d\.]+)[xX]", str, re.MULTILINE)
print(m)

for ip in m:
    print(ip)

Output

['192.168.0.16', '192.168.0.18']
192.168.0.16
192.168.0.18
Related