Important

This documentation covers IPython versions 6.0 and higher. Beginning with version 6.0, IPython stopped supporting compatibility with Python versions lower than 3.3 including all versions of Python 2.7.

If you are looking for an IPython version compatible with Python 2.7, please use the IPython 5.x LTS release and refer to its documentation (LTS is the long term support release).

Module: utils.text

Utilities for working with strings and text.

Inheritance diagram:

Inheritance diagram of IPython.utils.text

5 Classes

class IPython.utils.text.LSString

Bases: str

String derivative with a special access attributes.

These are normal strings, but with the special attributes:

.l (or .list) : value as list (split on newlines). .n (or .nlstr): original value (the string itself). .s (or .spstr): value as whitespace-separated string. .p (or .paths): list of path objects (requires path.py package)

Any values which require transformations are computed only once and cached.

Such strings are very useful to efficiently interact with the shell, which typically only understands whitespace-separated options for commands.

class IPython.utils.text.SList(iterable=(), /)

Bases: list

List derivative with a special access attributes.

These are normal lists, but with the special attributes:

  • .l (or .list) : value as list (the list itself).

  • .n (or .nlstr): value as a string, joined on newlines.

  • .s (or .spstr): value as a string, joined on spaces.

  • .p (or .paths): list of path objects (requires path.py package)

Any values which require transformations are computed only once and cached.

fields(*fields)

Collect whitespace-separated fields from string list

Allows quick awk-like usage of string lists.

Example data (in var a, created by ‘a = !ls -l’):

-rwxrwxrwx  1 ville None      18 Dec 14  2006 ChangeLog
drwxrwxrwx+ 6 ville None       0 Oct 24 18:05 IPython
  • a.fields(0) is ['-rwxrwxrwx', 'drwxrwxrwx+']

  • a.fields(1,0) is ['1 -rwxrwxrwx', '6 drwxrwxrwx+'] (note the joining by space).

  • a.fields(-1) is ['ChangeLog', 'IPython']

IndexErrors are ignored.

Without args, fields() just split()’s the strings.

grep(pattern, prune=False, field=None)

Return all strings matching ‘pattern’ (a regex or callable)

This is case-insensitive. If prune is true, return all items NOT matching the pattern.

If field is specified, the match must occur in the specified whitespace-separated field.

Examples:

a.grep( lambda x: x.startswith('C') )
a.grep('Cha.*log', prune=1)
a.grep('chm', field=-1)
sort(field=None, nums=False)

sort by specified fields (see fields())

Example:

a.sort(1, nums = True)

Sorts a by second field, in numerical order (so that 21 > 3)

class IPython.utils.text.EvalFormatter

Bases: Formatter

A String Formatter that allows evaluation of simple expressions.

Note that this version interprets a : as specifying a format string (as per standard string formatting), so if slicing is required, you must explicitly create a slice.

This is to be used in templating cases, such as the parallel batch script templates, where simple arithmetic on arguments is useful.

Examples

In [1]: f = EvalFormatter()
In [2]: f.format('{n//4}', n=8)
Out[2]: '2'

In [3]: f.format("{greeting[slice(2,4)]}", greeting="Hello")
Out[3]: 'll'
class IPython.utils.text.FullEvalFormatter

Bases: Formatter

A String Formatter that allows evaluation of simple expressions.

Any time a format key is not found in the kwargs, it will be tried as an expression in the kwargs namespace.

Note that this version allows slicing using [1:2], so you cannot specify a format string. Use EvalFormatter to permit format strings.

Examples

In [1]: f = FullEvalFormatter()
In [2]: f.format('{n//4}', n=8)
Out[2]: '2'

In [3]: f.format('{list(range(5))[2:4]}')
Out[3]: '[2, 3]'

In [4]: f.format('{3*2}')
Out[4]: '6'
class IPython.utils.text.DollarFormatter

Bases: FullEvalFormatter

Formatter allowing Itpl style $foo replacement, for names and attribute access only. Standard {foo} replacement also works, and allows full evaluation of its arguments.

Examples

In [1]: f = DollarFormatter()
In [2]: f.format('{n//4}', n=8)
Out[2]: '2'

In [3]: f.format('23 * 76 is $result', result=23*76)
Out[3]: '23 * 76 is 1748'

In [4]: f.format('$a or {b}', a=1, b=2)
Out[4]: '1 or 2'

12 Functions

IPython.utils.text.indent(instr, nspaces=4, ntabs=0, flatten=False)

Indent a string a given number of spaces or tabstops.

indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.

Parameters:
  • instr (basestring) – The string to be indented.

  • nspaces (int (default: 4)) – The number of spaces to be indented.

  • ntabs (int (default: 0)) – The number of tabs to be indented.

  • flatten (bool (default: False)) – Whether to scrub existing indentation. If True, all lines will be aligned to the same indentation. If False, existing indentation will be strictly increased.

Returns:

str|unicode

Return type:

string indented by ntabs and nspaces.

IPython.utils.text.list_strings(arg)

Always return a list of strings, given a string or list of strings as input.

Examples

In [7]: list_strings('A single string')
Out[7]: ['A single string']

In [8]: list_strings(['A single string in a list'])
Out[8]: ['A single string in a list']

In [9]: list_strings(['A','list','of','strings'])
Out[9]: ['A', 'list', 'of', 'strings']
IPython.utils.text.marquee(txt='', width=78, mark='*')

Return the input string centered in a ‘marquee’.

Examples

In [16]: marquee('A test',40)
Out[16]: '**************** A test ****************'

In [17]: marquee('A test',40,'-')
Out[17]: '---------------- A test ----------------'

In [18]: marquee('A test',40,' ')
Out[18]: '                 A test                 '
IPython.utils.text.num_ini_spaces(strng)

Return the number of initial spaces in a string

IPython.utils.text.format_screen(strng)

Format a string for screen printing.

This removes some latex-type format codes.

IPython.utils.text.dedent(text: str) str

Equivalent of textwrap.dedent that ignores unindented first line.

This means it will still dedent strings like: ‘’’foo is a bar ‘’’

For use in wrap_paragraphs.

IPython.utils.text.wrap_paragraphs(text, ncols=80)

Wrap multiple paragraphs to fit a specified width.

This is equivalent to textwrap.wrap, but with support for multiple paragraphs, as separated by empty lines.

Return type:

list of complete paragraphs, wrapped to fill ncols columns.

IPython.utils.text.strip_email_quotes(text)

Strip leading email quotation characters (‘>’).

Removes any combination of leading ‘>’ interspersed with whitespace that appears identically in all lines of the input text.

Parameters:

text (str) –

Examples

Simple uses:

In [2]: strip_email_quotes('> > text')
Out[2]: 'text'

In [3]: strip_email_quotes('> > text\n> > more')
Out[3]: 'text\nmore'

Note how only the common prefix that appears in all lines is stripped:

In [4]: strip_email_quotes('> > text\n> > more\n> more...')
Out[4]: '> text\n> more\nmore...'

So if any line has no quote marks (‘>’), then none are stripped from any of them

In [5]: strip_email_quotes('> > text\n> > more\nlast different')
Out[5]: '> > text\n> > more\nlast different'
IPython.utils.text.strip_ansi(source)

Remove ansi escape codes from text.

Parameters:

source (str) – Source to remove the ansi from

IPython.utils.text.compute_item_matrix(items, row_first: bool = False, empty=None, *, separator_size=2, displaywidth=80) Tuple[List[List[int]], Dict[str, int]]

Returns a nested list, and info to columnize items

Parameters:
  • items – list of strings to columize

  • row_first ((default False)) – Whether to compute columns for a row-first matrix instead of column-first (default).

  • empty ((default None)) – default value to fill list if needed

  • separator_size (int (default=2)) – How much characters will be used as a separation between each columns.

  • displaywidth (int (default=80)) – The width of the area onto which the columns should enter

Returns:

  • strings_matrix – nested list of string, the outer most list contains as many list as rows, the innermost lists have each as many element as columns. If the total number of elements in items does not equal the product of rows*columns, the last element of some lists are filled with None.

  • dict_info – some info to make columnize easier:

    num_columns

    number of columns

    max_rows

    maximum number of rows (final number may be less)

    column_widths

    list of with of each columns

    optimal_separator_width

    best separator width between columns

Examples

In [1]: l = ['aaa','b','cc','d','eeeee','f','g','h','i','j','k','l']
In [2]: list, info = compute_item_matrix(l, displaywidth=12)
In [3]: list
Out[3]: [['aaa', 'f', 'k'], ['b', 'g', 'l'], ['cc', 'h', None], ['d', 'i', None], ['eeeee', 'j', None]]
In [4]: ideal = {'num_columns': 3, 'column_widths': [5, 1, 1], 'optimal_separator_width': 2, 'max_rows': 5}
In [5]: all((info[k] == ideal[k] for k in ideal.keys()))
Out[5]: True
IPython.utils.text.columnize(items: List[str], row_first: bool = False, separator: str = '  ', displaywidth: int = 80, spread: bool = False)

Transform a list of strings into a single string with columns.

Parameters:
  • items (sequence of strings) – The strings to process.

  • row_first ((default False)) – Whether to compute columns for a row-first matrix instead of column-first (default).

  • separator (str, optional [default is two spaces]) – The string that separates columns.

  • displaywidth (int, optional [default is 80]) – Width of the display in number of characters.

Return type:

The formatted string.

IPython.utils.text.get_text_list(list_, last_sep=' and ', sep=', ', wrap_item_with='')

Return a string with a natural enumeration of items

>>> get_text_list(['a', 'b', 'c', 'd'])
'a, b, c and d'
>>> get_text_list(['a', 'b', 'c'], ' or ')
'a, b or c'
>>> get_text_list(['a', 'b', 'c'], ', ')
'a, b, c'
>>> get_text_list(['a', 'b'], ' or ')
'a or b'
>>> get_text_list(['a'])
'a'
>>> get_text_list([])
''
>>> get_text_list(['a', 'b'], wrap_item_with="`")
'`a` and `b`'
>>> get_text_list(['a', 'b', 'c', 'd'], " = ", sep=" + ")
'a + b + c = d'