strup — API¶
strup is a package for unpacking basic data objects from a text string.
strup is written by Jens B. Helmers (c) 2020
SPDX-License-Identifier: MIT
The function unpack¶
-
strup.unpack(fmt, text, *args, **kwargs)¶ Extract basic data types from text based on fmt.
- Parameters
fmt (str) – fmt[i] defines the type of item i in the output tuple. fmt[i] must be ‘i’, ‘f’, ‘s’, ‘?’ or ‘.’. Item i will be ignored if fmt[i]==’.’.
text (str) – The text string to extract the objects from
- Other Parameters
*args (list, optional) – Additional variable length argument list to be submitted to the constructor of Unpack
**kwargs (dict, optional) – Additional keyword arguments to be submitted to the constructor of Unpack
- Returns
The tuple of objects parsed from text.
- Return type
tuple
- Raises
ValueError – If any parsing error occur.
Examples
>>> unpack("ifs?", "5 2.3 ole True") (5, 2.3, 'ole', True) >>> unpack("isf", "100 'Donald Duck' 125.6", quote="'") (100, 'Donald Duck', 125.6)
The class Unpack¶
-
class
strup.Unpack(fmt, sep=None, none=False, quote=None, quote_escape=None)¶ Unpack is a Python package for unpacking basic data types from a text string.
Each item is of type ‘int’, ‘float’, ‘string’ or ‘bool’ depending on a format code in the constructor.
-
__init__(fmt, sep=None, none=False, quote=None, quote_escape=None)¶ Constructor for Unpack.
- Parameters
fmt (str) – fmt[i] defines the type of item i in the output tuple. fmt[i] must be ‘i’, ‘f’, ‘s’, ‘?’ or ‘.’. Item i will be ignored if fmt[i]==’.’.
sep (str or None, optional) – String to separate items. See string.split() method.
none (bool, optional) – If True: Zero-sized items are interpreted as None.
quote (str or None, optional) – String items are sometimes enclosed by quote characters. Quotes are mandatory if string items includes the sep or quote characters. A quote character inside an item must be escaped by ‘quote_escape’. (See example below). It is not possible to apply quotes if quote==’‘.
quote_escape (str or None, optional) – Typical values are ‘”“’, “’‘”, r’”’ or “’”. quote_escape = None is interpreted as quote_escape = quote*2
- Raises
ValueError – If any parsing error occur.
Examples
See the __call__() examples for application of these decoders:
>>> decode1 = Unpack('ifssis') >>> decode2 = Unpack('.fs', sep=',') >>> decode3 = Unpack('isfs', sep=' ', quote='"', quote_escape='""')
-
__call__(text)¶ Extract the tuple of objects by parsing text based on self._fmt
- Parameters
text (str) – The text string to extract the objects from
- Returns
The tuple of objects parsed from text.
- Return type
tuple
- Raises
ValueError – If any parsing error occur.
Examples
decode1, decode2 and decode3 as defined in the __init__() examples:
>>> decode1("3 4.5 ole dole 5 doffen") (3, 4.5, 'ole', 'dole', 5, 'doffen') >>> decode2("3,4.5, ole,dole,5,doffen") (4.5, ' ole') >>> decode3('3 "A ""quote"" test" 93.4 knut ignored') (3, 'A "quote" test', 93.4, 'knut')
-