Skip to content

Instantly share code, notes, and snippets.

@StanGenchev
Created April 22, 2021 11:44
Show Gist options
  • Save StanGenchev/5cd257c83c81e92047fdd6703e16e8fd to your computer and use it in GitHub Desktop.
Save StanGenchev/5cd257c83c81e92047fdd6703e16e8fd to your computer and use it in GitHub Desktop.
A python function which converts a string into a valid filename string.
import re
def get_valid_filename(string: str) -> str:
"""
Return the given string converted to a string that can be used for a clean
filename. Remove leading and trailing spaces; convert other spaces to
underscores; and remove anything that is not an alphanumeric, dash,
underscore, or dot.
>>> get_valid_filename("Cold/Freezing Location (between 50-14 F)")
'ColdFreezing_Location_between_50-14_F'
"""
string = str(re.sub(" +", " ", string)).strip().replace(" ", "_")
return re.sub(r"(?u)[^-\w.]", "", string)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment