How do I convert a string to a valid variable name in Python?

Well, I’d like to best Triptych’s solution with … a one-liner!

>>> def clean(varStr): return re.sub('\W|^(?=\d)','_', varStr)
...

>>> clean('32v2 g #Gmw845h$W b53wi ')
'_32v2_g__Gmw845h_W_b53wi_'

This substitution replaces any non-variable appropriate character with underscore and inserts underscore in front if the string starts with a digit. IMO, ‘name/with/slashes’ looks better as variable name name_with_slashes than as namewithslashes.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)