Inheritance diagram for IPython.utils.text:
Utilities for working with strings and text.
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’
x.__init__(...) initializes x; see help(type(x)) for signature
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’
x.__init__(...) initializes x; see help(type(x)) for signature
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’
x.__init__(...) initializes x; see help(type(x)) for signature
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.
x.__init__(...) initializes x; see help(type(x)) for signature
Return a copy of the string S with only its first character capitalized.
Return S centered in a string of length width. Padding is done using the specified fill character (default is a space)
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.
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.
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.
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.
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.
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.
Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{‘ and ‘}’).
Like S.find() but raise ValueError when the substring is not found.
Return True if all characters in S are alphanumeric and there is at least one character in S, False otherwise.
Return True if all characters in S are alphabetic and there is at least one character in S, False otherwise.
Return True if all characters in S are digits and there is at least one character in S, False otherwise.
Return True if all cased characters in S are lowercase and there is at least one cased character in S, False otherwise.
Return True if all characters in S are whitespace and there is at least one character in S, False otherwise.
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.
Return True if all cased characters in S are uppercase and there is at least one cased character in S, False otherwise.
Return a string which is the concatenation of the strings in the iterable. The separator between elements is S.
Return S left-justified in a string of length width. Padding is done using the specified fill character (default is a space).
Return a copy of the string S converted to lowercase.
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
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.
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.
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.
Like S.rfind() but raise ValueError when the substring is not found.
Return S right-justified in a string of length width. Padding is done using the specified fill character (default is a space)
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.
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.
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
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.
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.
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.
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
Return a copy of the string S with uppercase characters converted to lowercase and vice versa.
Return a titlecased version of S, i.e. words start with uppercase characters, all remaining cased characters have lowercase.
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.
Return a copy of the string S converted to uppercase.
Pad a numeric string S with zeros on the left, to fill a field of the specified width. The string S is never truncated.
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.
x.__init__(...) initializes x; see help(type(x)) for signature
L.append(object) – append object to end
L.extend(iterable) – extend list by appending elements from the iterable
Collect whitespace-separated fields from string list
Allows quick awk-like usage of string lists.
-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.
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)
Raises ValueError if the value is not present.
L.insert(index, object) – insert object before index
Raises IndexError if list is empty or index is out of range.
L.remove(value) – remove first occurrence of value. Raises ValueError if the value is not present.
L.reverse() – reverse IN PLACE
sort by specified fields (see fields())
Sorts a by second field, in numerical order (so that 21 > 3)
Transform a list of strings into a single string with columns.
Parameters : | items : sequence of strings
separator : str, optional [default is two spaces]
displaywidth : int, optional [default is 80]
|
---|---|
Returns : | The formatted string. : |
Returns a nested list, and info to columnize items
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.
Return grep() on dir()+dir(__builtins__).
A very common use of grep() when working interactively.
Return the input string with single and double quotes escaped out
Format a string for screen printing.
This removes some latex-type format codes.
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.
Case-insensitive dgrep()
Synonym for case-insensitive grep.
Indent a string a given number of spaces or tabstops.
indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
Parameters : | instr : basestring
nspaces : int (default: 4)
ntabs : int (default: 0)
flatten : bool (default: False)
|
---|---|
Returns : | str|unicode : string indented by ntabs and nspaces. |
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’] |
---|
Return the longest common substring in a list of strings.
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 ‘ |
---|
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.
Return the number of initial spaces in a string
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']
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.
Calls qw(words) in flat mode. It’s just a convenient shorthand.
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'
Remove a single pair of quotes from the endpoints of a string.
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. : |
---|