If I have a string of Python code, how do I tell if it is valid, i.e., if entered at the Python prompt, it would raise a SyntaxError or not? I thought that using compiler.parse
would work, but apparently that module has been removed in Python 3. Is there a way to do it that also works in Python 3. Obviously, I don't want to execute the code, just check its syntax.
Using Python's "in" operator The simplest and fastest way to check whether a string contains a substring or not in Python is the "in" operator . This operator returns true if the string contains the characters, otherwise, it returns false .
Python String isidentifier() MethodA string is considered a valid identifier if it only contains alphanumeric letters (a-z) and (0-9), or underscores (_). A valid identifier cannot start with a number, or contain any spaces.
Using in operator The Pythonic, fast way to check for the specific character in a string uses the in operator. It returns True if the character is found in the string and False otherwise. ch = '. '
Use ast.parse
:
import ast
def is_valid_python(code):
try:
ast.parse(code)
except SyntaxError:
return False
return True
>>> is_valid_python('1 // 2')
True
>>> is_valid_python('1 /// 2')
False
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With