I am looking for a specific string in text, and want to get it only if found.
I can write it as followד and it works:
if re.search("Counter=(d+)", line): total = int(re.search("Counter=(d+)", line).group(1)) else: total = 1
But I remember another nicer way to write it with question mark before the “group”, and put value “1” as default value in case of re.search
return an empty result.
Advertisement
Answer
When using re.findall
it will return a list with groups or empty.
Then you can conditionally assign based on this list using a ternary expression:
counters = re.findall("Counter=(d+)", line) total = counters[0] if counters else 1
(This will also work in Python before 3.8.)
Test with both cases:
counters = re.findall("Counter=(d+)", 'Hello World') total = counters[0] if counters else 1 print(total) # 1 counters = re.findall("Counter=(d+)", 'Counter=100') total = counters[0] if counters else 1 print(total) # 100