3

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
toolic
  • 46,418
  • 10
  • 64
  • 104

3 Answers3

5

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 '='

Frank Yellin
  • 3,214
  • 1
  • 7
  • 15
  • Dude! Excellent! I will look into 3.8! – StepAndFetchit Nov 11 '20 at 19:14
  • 2
    @StepAndFetchit If this answer [addressed your problem](https://stackoverflow.com/help/someone-answers), please consider [accepting it](https://meta.stackexchange.com/questions/5234) by clicking on the check mark/tick to the left of the answer, turning it green. This marks the question as resolved to your satisfaction, and awards [reputation](https://stackoverflow.com/help/whats-reputation) both to you and the person who answered. Once you have >= 15 reputation points, you may also upvote the answer if you wish. There is no obligation to do either. – MattDMo Nov 12 '20 at 00:31
3

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
choroba
  • 200,498
  • 20
  • 180
  • 248
-1

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
Polar Bear
  • 4,457
  • 1
  • 3
  • 11