xoutil.eight.string - Checkers for simple types

Technical string handling.

Technical strings are those that requires to be instances of str standard type. See String Ambiguity in Python for more information.

This module will be used mostly as a namespace, for example:

from xoutil.eight import string
Foobar.__name__ = string.force(class_name)

If these functions are going to be used standalone, do something like:

from xoutil.eight.string import force as force_str
Foobar.__name__ = force_str(class_name)
xoutil.eight.string.check_identifier(s)[source]

Check if s is a valid identifier.

xoutil.eight.string.force(value='', encoding=None)[source]

Convert any value to standard str type in a safe way.

This function is useful in some scenarios that require str type (for example attribute __name__ in functions and types).

As str is bytes in Python 2, using str(value) assures correct these scenarios in most cases, but in other is not enough, for example:

>>> from xoutil.eight import string
>>> def inverted_partial(func, *args, **keywords):
...     def inner(*a, **kw):
...         a += args
...         kw.update(keywords)
...         return func(*a, **kw)
...     name = func.__name__.replace('lambda', u'λ')
...     inner.__name__ = string.force(name)
...     return inner

Changed in version 1.9.6: Add the ‘enconding’ parameter.

xoutil.eight.string.force_ascii(value, encoding=None)[source]

Return the string normal form for the value

Convert all non-ascii to valid characters using unicode ‘NFKC’ normalization.

Parameters:encoding – If value is not a text (unicode), it is decoded before ASCII normalization using this encoding. If not provided use the return of force_encoding().

Changed in version 1.8.7: Add parameter ‘encoding’.

xoutil.eight.string.isfullidentifier(s)[source]

Check if arg is a valid dotted Python identifier.

See isidentifier() for what “validity” means.

xoutil.eight.string.isidentifier(s)[source]

If s is a valid identifier according to the language definition.

xoutil.eight.string.safe_isfullidentifier(s)[source]

Check if arg is a valid dotted Python identifier.

Check before if s is instance of string types. See safe_isidentifier() for what “validity” means.

xoutil.eight.string.safe_isidentifier(s)[source]

If s is a valid identifier according to the language definition.

Check before if s is instance of string types.

xoutil.eight.string.safe_join(separator, iterable, encoding=None)[source]

Similar to join method in string objects.

The semantics is equivalent to separator.join(iterable) but forcing separator and items to be of str standard type.

For example:

>>> safe_join('-', range(6))
'0-1-2-3-4-5'

Check that the expression '-'.join(range(6)) raises a TypeError.

Changed in version 1.9.6: Add the ‘enconding’ parameter.