defstand_strings(str_list,delim):"""Standardize capitalization and word delimiters for a list of strings. Args: str_list (list): A list of of input strings. delim (char): The desired output word delimiter - must be one of ' ' (i.e. space), '-', '_', or '.' Returns: List of input strings, converted to uppercase with word delimiters converted to the user's chosen delimiter. Depends: Modules re and sys. Examples: >>>import re >>>import sys >>>ny = [' New York City ', 'New-York_City', 'new.york.city'] >>>print(stand_strings(ny, "_")) ['NEW_YORK_CITY', 'NEW_YORK_CITY', 'NEW_YORK_CITY'] """## Check for appropriate word delimiter selectionifdelimnotin[' ','-','_','.']:sys.exit('''Please select one of the following for the output word delimiter: " " (space), "-", "_", "." ''')## Convert to uppercase, strip leading/trailing whitespace str_list=[x.upper().strip()forxinstr_list]## Replace emdashes with hyphensstr_list=[str.replace('--','-')forxinstr_list]## Remove non-ASCII characters## HAVEN'T PERSONALLY TESTED THIS YET## Got solution from https://yuji.wordpress.com/2010/01/28/python-sql-remove-all-non-ascii-characters-from-string/forsinstr_lists=''.join([xforxinsiford(x)<128])## Swap out whitespace, dash, period, underscore for selected delimiterstr_list=[re.sub('\s|\.|-|_',delim,x)forxinstr_list]returnstr_list
Comments (0)
HTTPSSSH
You can clone a snippet to your computer for local editing.
Learn more.