Updated Answer
Since my original answer, you've added seven new requirements to this question. I'm disengaging as I think you need to better understand the scope of the problem you're facing before asking for more help.
However, I will throw one more snippet up that might set you on the right path, as it appears that you're trying to find valid mathematical expressions. The following code will do that:
def check_valid(data):
errors = (SyntaxError, NameError)
try:
eval(data)
except errors:
for i in data.split():
try:
eval(i)
except errors:
return None
return data
test = ["4++2", "4+-2", "4.0 + 2", "3.88327 - $3.4", "a + 24", "2+6", "4+/3"]
for t in test:
try:
assert check_valid(t)
print(f"{t} valid")
except AssertionError:
print(f"{t} not valid")
Output
4++2 valid
4+-2 valid
4.0 + 2 valid
3.88327 - $3.4 not valid
a + 24 not valid
2+6 valid
4+/3 not valid
In Python, + can repeat any number of times and still be a valid math expression, as it's just changing the sign of the integer repeatedly.
Original Answer
There are a number of ways to approach this. Given your example, there are a few flaws in your logic:
- "4.0" is not numeric. Numeric is in 0-9 or unicode numerics. Docs here
- You're checking a string against another string with the
in
keyword. With your first example string, the sequence "4.0" is clearly not in the sequence "*^-+/()". Example of how this works:
>>> "4.0" in "asdf4.012345"
True
>>> "4.0" in "0.4"
False
A quick fix using similar logic would be to check character-by-character rather than word-by-word, and combine the two conditionals with and
. Try the following snippet:
def check_valid(data):
for word in data.split():
for character in word:
if character not in "*^-+/()." and not character.isnumeric():
return None
return data
test = ["4.0 + 2", "3.88327 - $3.4", "a + 24", "22 66", "2+6"]
for t in test:
print(f"Test: {check_valid(t)}")
Output
Test: 4.0 + 2
Test: None
Test: None
Test: 22 66
Test: 2+6
Note: I changed some names to more closely follow python code style best practices.