Home:ALL Converter>String treatment with blacklist and whitelist in Python

String treatment with blacklist and whitelist in Python

Ask Time:2019-08-29T04:02:38         Author:Gastyr

Json Formatter

I am creating a program, and I need to create a logic that handles user input for the eval() function. The input will be a math function, I want to handle some irregularities and make sure the string is a math function and not malicious code.

For this I created a logic that compares all characters of the string with blacklist and whitelist, the problem is that the string can only contain a few characters in a specific arrangement, for example cos, the string cannot contain c + o * s.

whitelist = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '(', ')',
            'x', 'y', 'sin', 'cos', 'tg', '+', '-', '*', '/', ' ']

blacklist = ['a', 'b', 'd', 'f', 'h', 'i', 'j', 'k', 'l', 'm', 'p', 'q',
            'r', 'u', 'v', 'w', 'z']

def stringTreat(string):
    if not any(ch in string for ch in blacklist):
        if all(ch in whitelist for ch in string):
            print('OK!!')
        else:
            print('stop at whitelist')
    else:
        print('stop at blacklist')

string = input('input:')

stringTreat(string)

If I set 12 + 67 - 82 to the input of this example, the output is OK!!, but if cos(x) is the input, the output changes to stop at whitelist.

How can I create a logic to accept substrings e.g. (sin, cos, tg), characters e.g. (0, 1, 2, 3...) and doesn't accept other substrings and characters e.g. (a, f, @, $, ls, mv)?

Author:Gastyr,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/57699348/string-treatment-with-blacklist-and-whitelist-in-python
yy