Inheritance diagram for IPython.utils.text:
Utilities for working with strings and text.
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.
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(‘{range(3)}’) Out[3]: ‘[0, 1, 2]’
In [4]: f.format(‘{3*2}’) Out[4]: ‘6’
x.__init__(...) initializes x; see x.__class__.__doc__ 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 x.__class__.__doc__ for signature
S.capitalize() -> string
Return a copy of the string S with only its first character capitalized.
S.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)
S.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.
S.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.
S.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.
S.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.
S.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.
S.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.
S.index(sub [,start [,end]]) -> int
Like S.find() but raise ValueError when the substring is not found.
S.isalnum() -> bool
Return True if all characters in S are alphanumeric and there is at least one character in S, False otherwise.
S.isalpha() -> bool
Return True if all characters in S are alphabetic and there is at least one character in S, False otherwise.
S.isdigit() -> bool
Return True if all characters in S are digits and there is at least one character in S, False otherwise.
S.islower() -> bool
Return True if all cased characters in S are lowercase and there is at least one cased character in S, False otherwise.
S.isspace() -> bool
Return True if all characters in S are whitespace and there is at least one character in S, False otherwise.
S.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.
S.isupper() -> bool
Return True if all cased characters in S are uppercase and there is at least one cased character in S, False otherwise.
S.join(iterable) -> string
Return a string which is the concatenation of the strings in the iterable. The separator between elements is S.
S.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).
S.lower() -> string
Return a copy of the string S converted to lowercase.
S.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
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.
S.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.
S.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.
S.rindex(sub [,start [,end]]) -> int
Like S.rfind() but raise ValueError when the substring is not found.
S.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)
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.
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.
S.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.
S.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.
S.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.
S.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
S.swapcase() -> string
Return a copy of the string S with uppercase characters converted to lowercase and vice versa.
S.title() -> string
Return a titlecased version of S, i.e. words start with uppercase characters, all remaining cased characters have lowercase.
S.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.
S.upper() -> string
Return a copy of the string S converted to uppercase.
S.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.
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 x.__class__.__doc__ for signature
L.append(object) – append object to end
L.count(value) -> integer – return number of occurrences of value
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)
L.index(value, [start, [stop]]) -> integer – return first index of value. Raises ValueError if the value is not present.
L.insert(index, object) – insert object before index
L.pop([index]) -> item – remove and return item at index (default last). 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)
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 string s in appropriate quotes, using raw string if possible.
XXX - example removed because it caused encoding errors in documentation generation. We need a new example that doesn’t contain invalid chars.
Note the use of raw string and padding at the end to allow trailing backslash.
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.
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. : |
---|