darbia.utils.strings
#
Assorted utility functions.
Module Contents#
Classes#
A custom JSON encoder that attempts to convert all user defined classes to string. |
Functions#
|
Generate a random string of the specified length using the specified character set. |
|
Split a string into alpha prefix and numeric suffix. |
|
Find the nth occurrence of a substring in a string. |
|
Remove all substrings from a string. |
|
Generate a series of formatted strings from an iterable. |
Attributes#
- darbia.utils.strings.random_string(length: int = 6, characters: str = string.ascii_uppercase) str [source]#
Generate a random string of the specified length using the specified character set.
- Parameters:
length – The desired length.
characters – The character set.
- Returns:
result – A random string.
- Return type:
Examples
>>> random_string(length=1, characters='a') 'a'
- darbia.utils.strings.split_prefix_and_number(text: str) tuple[str, int] [source]#
Split a string into alpha prefix and numeric suffix.
- Parameters:
text (str) – The text to split
- Returns:
prefix, number – The prefix and the number
- Return type:
Examples
>>> split_prefix_and_number('U1500000') ('U', 1500000)
- class darbia.utils.strings.CustomEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]#
Bases:
json.JSONEncoder
A custom JSON encoder that attempts to convert all user defined classes to string.
- darbia.utils.strings.find_nth(haystack: str, needle: str, nth: int) int [source]#
Find the nth occurrence of a substring in a string.
- Parameters:
haystack – The string to search in
needle – The substring to search for
nth – Which nth occurrence to find
- Return type:
The index of the nth occurrence of the substring, or -1 if not found.
Examples
>>> find_nth("yankee doodle", "o", 2) 9
- darbia.utils.strings.bulk_substring_remove(text: str, substrings: list[str]) str [source]#
Remove all substrings from a string.
- Parameters:
text – The string to update
substrings – The substrings to remove
- Return type:
The original string with all substrings removed
Examples
>>> bulk_substring_remove("yankee doodle", ["yan", "dle"]) 'kee doo'
- darbia.utils.strings.prefix_zfilled(prefix: str, iterable: collections.abc.Iterable, sep: str = '-', zeroes: int = 3) collections.abc.Iterable[str] [source]#
Generate a series of formatted strings from an iterable.
- Parameters:
prefix – The text to prefix to each item
iterable – The items to iterate over
sep – The seperator between the prefix and the iterable
zeroes – The number of zeros to zfill the iterable with
- Yields:
The items from the iterable with formatting
Examples
>>> list(prefix_zfilled("x", range(50, 53))) ['x-050', 'x-051', 'x-052']