Skip to content

Instantly share code, notes, and snippets.

@tizz98
Last active October 25, 2017 20:24
Show Gist options
  • Save tizz98/706d26a5911c359503c5ca14d18b46fd to your computer and use it in GitHub Desktop.
Save tizz98/706d26a5911c359503c5ca14d18b46fd to your computer and use it in GitHub Desktop.
Will convert a string to valid python class and/or variable names. (useful for convention over configuration)
def clean_name(name, replacement_char):
# Remove invalid characters
new_class_name = re.sub('[^0-9a-zA-Z_]', replacement_char, name)
# Remove leading characters until we find a letter or underscore
return re.sub('^[^a-zA-Z_]+', replacement_char, new_class_name)
print(clean_name('123something** cool\\vv__', '*').title().replace('*', '')) # CamelCase
print(clean_name('123something** cool\\vv__', '_')) # snake_case
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment