B
B
bittenmuskrat2020-04-22 01:27:59
Python
bittenmuskrat, 2020-04-22 01:27:59

How to solve problem with output condition and regular expressions in Python?

import re

m_list = ["yellow\?", "red\?", "blue\?"]
data = input().lower()
a = re.search("black\?", data)
print("Yes occurrence" if a else "No occurrence")

1) I'm trying to make print not output the else block and print only the value when the regular expression pattern matches. Attempts to remove the else block, or to replace "No entry" with pass or None - give an error.

2) How to pass the m_list array to the re.search conditions so that the regular expression checks the text against all elements specified in m_list?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Pankov, 2020-04-22
@bittenmuskrat

one)

Attempts to remove the else block, or to replace "No entry" with pass or None - give an error.

a if q else bis a ternary operator. It has three arguments (a, b, q) and the result is either a or b depending on whether q is true .
pass syntax is not suitable there, because it is not a value, but a keyword.
You need to evaluate an expression and the result must be something that can be passed to print(). If else you specify an empty string "", then print will print it. I don't know if an empty paragraph in the console will suit you. If not, then see the solution suggested above.
2) in the previous solution, you might not have noticed, but the regexps are connected through "|". This will not work for all regexps. You have to be careful with this kind of concatenation. In general, you need to be careful with regexps. Great power has great responsibility.
You can loop and search for each regexp individually. This makes it easier for you to maintain control over what you find and how you react to it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question