Created
April 22, 2021 11:44
-
-
Save StanGenchev/5cd257c83c81e92047fdd6703e16e8fd to your computer and use it in GitHub Desktop.
A python function which converts a string into a valid filename string.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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