I have a string and want to check if it can be used as a valid variable without getting a syntax error. For example
def variableName(string):
#if string is valid variable name:
#return True
#else:
#return False
input >>> variableName("validVariable")
output >>> True
input >>> variableName("992variable")
output >>> False
I would not like to use the .isidentifier(). I want to make a function of my own.
The following answer is true only for "old-style" Python-2.7 identifiers;
"validVariable".isidentifier()
#True
"992variable".isidentifier()
#False
Since you changed your question after I posted the answer, consider writing a regular expression:
re.match(r"[_a-z]\w*$", yourstring,flags=re.I)
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