IPython Documentation

Table Of Contents

Previous topic

utils.terminal

Next topic

utils.timing

This Page

utils.text

Module: utils.text

Inheritance diagram for IPython.utils.text:

Utilities for working with strings and text.

Classes

DollarFormatter

class IPython.utils.text.DollarFormatter

Bases: IPython.utils.text.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]: u‘2’

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

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

__init__()

x.__init__(...) initializes x; see help(type(x)) for signature

check_unused_args(used_args, args, kwargs)
convert_field(value, conversion)
format(format_string, *args, **kwargs)
format_field(value, format_spec)
get_field(field_name, args, kwargs)
get_value(key, args, kwargs)
parse(fmt_string)
skip_doctest = False
vformat(format_string, args, kwargs)

EvalFormatter

class IPython.utils.text.EvalFormatter

Bases: string.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’

__init__()

x.__init__(...) initializes x; see help(type(x)) for signature

check_unused_args(used_args, args, kwargs)
convert_field(value, conversion)
format(format_string, *args, **kwargs)
format_field(value, format_spec)
get_field(name, args, kwargs)
get_value(key, args, kwargs)
parse(format_string)
vformat(format_string, args, kwargs)

FullEvalFormatter

class IPython.utils.text.FullEvalFormatter

Bases: string.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]: u‘2’

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

In [4]: f.format(‘{3*2}’) Out[4]: u‘6’

__init__()

x.__init__(...) initializes x; see help(type(x)) for signature

check_unused_args(used_args, args, kwargs)
convert_field(value, conversion)
format(format_string, *args, **kwargs)
format_field(value, format_spec)
get_field(field_name, args, kwargs)
get_value(key, args, kwargs)
parse(format_string)
skip_doctest = False
vformat(format_string, args, kwargs)

LSString

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

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.

__init__()

x.__init__(...) initializes x; see help(type(x)) for signature

capitalize() → string

Return a copy of the string S with only its first character capitalized.

center(width[, fillchar]) → string

Return S centered in a string of length width. Padding is done using the specified fill character (default is a space)

count(sub[, start[, end]]) → int

Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.

decode([encoding[, errors]]) → object

Decodes S using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is ‘strict’ meaning that encoding errors raise a UnicodeDecodeError. Other possible values are ‘ignore’ and ‘replace’ as well as any other name registered with codecs.register_error that is able to handle UnicodeDecodeErrors.

encode([encoding[, errors]]) → object

Encodes S using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that is able to handle UnicodeEncodeErrors.

endswith(suffix[, start[, end]]) → bool

Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.

expandtabs([tabsize]) → string

Return a copy of S where all tab characters are expanded using spaces. If tabsize is not given, a tab size of 8 characters is assumed.

find(sub[, start[, end]]) → int

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

format(*args, **kwargs) → string

Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{‘ and ‘}’).

get_list()
get_nlstr()
get_paths()
get_spstr()
index(sub[, start[, end]]) → int

Like S.find() but raise ValueError when the substring is not found.

isalnum() → bool

Return True if all characters in S are alphanumeric and there is at least one character in S, False otherwise.

isalpha() → bool

Return True if all characters in S are alphabetic and there is at least one character in S, False otherwise.

isdigit() → bool

Return True if all characters in S are digits and there is at least one character in S, False otherwise.

islower() → bool

Return True if all cased characters in S are lowercase and there is at least one cased character in S, False otherwise.

isspace() → bool

Return True if all characters in S are whitespace and there is at least one character in S, False otherwise.

istitle() → bool

Return True if S is a titlecased string and there is at least one character in S, i.e. uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return False otherwise.

isupper() → bool

Return True if all cased characters in S are uppercase and there is at least one cased character in S, False otherwise.

join(iterable) → string

Return a string which is the concatenation of the strings in the iterable. The separator between elements is S.

l
list
ljust(width[, fillchar]) → string

Return S left-justified in a string of length width. Padding is done using the specified fill character (default is a space).

lower() → string

Return a copy of the string S converted to lowercase.

lstrip([chars]) → string or unicode

Return a copy of the string S with leading whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is unicode, S will be converted to unicode before stripping

n
nlstr
p
partition(sep) -> (head, sep, tail)

Search for the separator sep in S, and return the part before it, the separator itself, and the part after it. If the separator is not found, return S and two empty strings.

paths
replace(old, new[, count]) → string

Return a copy of string S with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

rfind(sub[, start[, end]]) → int

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

rindex(sub[, start[, end]]) → int

Like S.rfind() but raise ValueError when the substring is not found.

rjust(width[, fillchar]) → string

Return S right-justified in a string of length width. Padding is done using the specified fill character (default is a space)

rpartition(sep) -> (head, sep, tail)

Search for the separator sep in S, starting at the end of S, and return the part before it, the separator itself, and the part after it. If the separator is not found, return two empty strings and S.

rsplit([sep[, maxsplit]]) → list of strings

Return a list of the words in the string S, using sep as the delimiter string, starting at the end of the string and working to the front. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator.

rstrip([chars]) → string or unicode

Return a copy of the string S with trailing whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is unicode, S will be converted to unicode before stripping

s
split([sep[, maxsplit]]) → list of strings

Return a list of the words in the string S, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result.

splitlines([keepends]) → list of strings

Return a list of the lines in S, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true.

spstr
startswith(prefix[, start[, end]]) → bool

Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.

strip([chars]) → string or unicode

Return a copy of the string S with leading and trailing whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is unicode, S will be converted to unicode before stripping

swapcase() → string

Return a copy of the string S with uppercase characters converted to lowercase and vice versa.

title() → string

Return a titlecased version of S, i.e. words start with uppercase characters, all remaining cased characters have lowercase.

translate(table[, deletechars]) → string

Return a copy of the string S, where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256 or None. If the table argument is None, no translation is applied and the operation simply removes the characters in deletechars.

upper() → string

Return a copy of the string S converted to uppercase.

zfill(width) → string

Pad a numeric string S with zeros on the left, to fill a field of the specified width. The string S is never truncated.

SList

class IPython.utils.text.SList

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

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

__init__()

x.__init__(...) initializes x; see help(type(x)) for signature

append()

L.append(object) – append object to end

count(value) → integer -- return number of occurrences of value
extend()

L.extend(iterable) – extend list by appending elements from the iterable

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.

get_list()
get_nlstr()
get_paths()
get_spstr()
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)
index(value[, start[, stop]]) → integer -- return first index of value.

Raises ValueError if the value is not present.

insert()

L.insert(index, object) – insert object before index

l
list
n
nlstr
p
paths
pop([index]) → item -- remove and return item at index (default last).

Raises IndexError if list is empty or index is out of range.

remove()

L.remove(value) – remove first occurrence of value. Raises ValueError if the value is not present.

reverse()

L.reverse() – reverse IN PLACE

s
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)

spstr

Functions

IPython.utils.text.columnize(items, separator=' ', displaywidth=80)

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

Parameters :

items : sequence of strings

The strings to process.

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.

Returns :

The formatted string. :

IPython.utils.text.compute_item_matrix(items, empty=None, *args, **kwargs)

Returns a nested list, and info to columnize items

IPython.utils.text.dedent(text)

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.dgrep(pat, *opts)

Return grep() on dir()+dir(__builtins__).

A very common use of grep() when working interactively.

IPython.utils.text.esc_quotes(strng)

Return the input string with single and double quotes escaped out

IPython.utils.text.format_screen(strng)

Format a string for screen printing.

This removes some latex-type format codes.

IPython.utils.text.grep(pat, list, case=1)

Simple minded grep-like function. grep(pat,list) returns occurrences of pat in list, None on failure.

It only does simple string matching, with no support for regexps. Use the option case=0 for case-insensitive matching.

IPython.utils.text.idgrep(pat)

Case-insensitive dgrep()

IPython.utils.text.igrep(pat, list)

Synonym for case-insensitive grep.

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 : 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.long_substr(data)

Return the longest common substring in a list of strings.

Credit: http://stackoverflow.com/questions/2892931/longest-common-substring-from-more-than-two-strings-python

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.native_line_ends(filename, backup=1)

Convert (in-place) a file to line-ends native to the current OS.

If the optional backup argument is given as false, no backup of the original file is left.

IPython.utils.text.num_ini_spaces(strng)

Return the number of initial spaces in a string

IPython.utils.text.qw(words, flat=0, sep=None, maxsplit=-1)

Similar to Perl’s qw() operator, but with some more options.

qw(words,flat=0,sep=’ ‘,maxsplit=-1) -> words.split(sep,maxsplit)

words can also be a list itself, and with flat=1, the output will be recursively flattened.

Examples:

>>> qw('1 2')
['1', '2']
>>> qw(['a b','1 2',['m n','p q']])
[['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
>>> qw(['a b','1 2',['m n','p q']],flat=1)
['a', 'b', '1', '2', 'm', 'n', 'p', 'q']
IPython.utils.text.qw_lol('a b') → [['a','b']],

otherwise it’s just a call to qw().

We need this to make sure the modules_some keys always end up as a list of lists.

IPython.utils.text.qwflat(words, sep=None, maxsplit=-1)

Calls qw(words) in flat mode. It’s just a convenient shorthand.

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.unquote_ends(istr)

Remove a single pair of quotes from the endpoints of a string.

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.

Returns :list of complete paragraphs, wrapped to fill `ncols` columns. :