Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3: How to check if a string can be a valid variable?

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.

like image 580
Radhe Krishna Avatar asked Dec 12 '25 08:12

Radhe Krishna


1 Answers

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)
like image 130
DYZ Avatar answered Dec 13 '25 21:12

DYZ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!