Python way to write two if statements

I have two variables that are the result of a regular expression search.

a = re.search('some regex', str)
b = re.search('different regex', str)

This should return a re object. If they are not None, I want to use the group () method to get the string that it matched. This is the code I'm using right now to do this:

if a != None:
   a = a.group()
if b != None:
   b = b.group()

Is there a smarter way to write these two if statements? Maybe combine them into one? I think that taking 4 lines for this is too verbose.

Thank.

+3
source share
5 answers

Do not obscure the built-in strand say

if a:

instead

if a != None

Nothing more to improve imho.

+5
source

a = a.group() if a else None

+4
source

:

a, b = a.group() if a else None, b.group() if b else None
+2

, a b Match . , , :

>>> def text_or_none(v): return v.group() if v is not None else None
>>> a = text_or_none(re.search("\d", "foo"))
None
>>> b = text_or_none(re.search("\w+", "foo"))
foo
+2

:

a, b = (var.group() if var is not None else None for var in (a,b) )

This saves the value of a if it is, for example, 0. This is the end of your query.

However, after a while I came up with this suggestion taking into account the context:

import re
target = """"Id","File","Easting","Northing","Alt","Omega","Phi","Kappa","Photo","Roll","Line","Roll_line","Orient","Camera"
1800,2008308_017_079.tif,530658.110,5005704.180,2031.100000,0.351440,-0.053710,0.086470,79,2008308,17,308_17,rightX,Jen73900229d
"""
print target
regs=(',(.*.tif)',',(left.*)',',(right.*)')
re_results=(result.group()
            for result in ((re.search(reg, target)
                            for reg in regs)
                           )
            if result is not None)
print list(re_results)
0
source

Source: https://habr.com/ru/post/1756605/


All Articles