String to valid Python identifier
"Martin v. Löwis"
martin at v.loewis.de
Thu Aug 6 04:24:08 EDT 2009
> Is there any easy function in the stdlib to convert any random string in
> a valid Python identifier .. possibly by replacing non-valid characters
> with _ ?
I think this is fairly underspecified as a problem statement. A solution
that would meet your specification would be
def mkident(s):
return "foo"
It returns a valid Python identifier for any random string.
If you now complain that this gives too many collisions, I propose
def mkident(s):
return "foo%d" % (hash(s) & 0x7fffffff)
Regards,
Martin
More information about the Python-list
mailing list