os_helper.string_utils module

String Utilities

Two small, easy-to-get-wrong checks come up constantly: “is this string actually empty” (if not s misses a string that is only whitespace, like "   "), and “can I safely use this string as a filename or a URL segment” (an accented or non-ASCII character can silently break a path on some filesystems or a query string on some servers).

emptystring() answers the first question in one call instead of a hand-rolled check every caller has to remember. asciistring() answers the second by folding accents to their plain-ASCII equivalent and replacing whatever is left over with a placeholder character, so the result is always safe to drop into a filename or URL.

Usage example

>>> import os_helper as osh
>>> osh.emptystring("   ")
True
>>> osh.asciistring("Café-Con-Leche!", replacement_char="_")
'cafe_con_leche'

Author

Warith HARCHAOUI, https://linkedin.com/in/warith-harchaoui

os_helper.string_utils.asciistring(input_string, replacement_char='-', lower=True, allow_digits=True)[source]

Convert a given string into a “safe” ASCII string by replacing accented and non-ASCII characters.

Non-ASCII characters that cannot be converted will be replaced with a specified character.

Parameters:
  • input_string (str) – The input string to be converted.

  • replacement_char (str, optional) – The character to replace non-ASCII or unwanted characters with. Defaults to ‘-‘.

  • lower (bool, optional) – Whether to convert the string to lowercase. Defaults to True.

  • allow_digits (bool, optional) – Whether to allow digits in the resulting string. Defaults to True.

Returns:

A “safe” ASCII string with unwanted characters replaced and case adjusted.

Return type:

str

Examples

>>> asciistring("MyFile@2024.txt")
'myfile-2024-txt'
>>> asciistring("Café-Con-Leche!", replacement_char="_")
'cafe_con_leche'
>>> asciistring("Special#File$2024", lower=False)
'Special-File-2024'
os_helper.string_utils.emptystring(s)[source]

Return True if s is None, not a string, or only whitespace.

Convenient for input validation where "", None and "   " should all be treated the same way.

Parameters:

s (Optional[str]) – The value to check.

Returns:

True when s is None or contains only whitespace; False otherwise.

Return type:

bool

Examples

>>> emptystring("")
True
>>> emptystring("   ")
True
>>> emptystring(None)
True
>>> emptystring("hello")
False