Markup Class

Inheritance diagram of Markup

class Markup

Marks a string as being safe for inclusion in HTML/XML output without needing to be escaped. This implements the __html__ interface a couple of frameworks and web applications use. Markup is a direct subclass of unicode and provides all the methods of unicode just that it escapes arguments passed and always returns Markup.

The escape function returns markup objects so that double escaping can’t happen.

The constructor of the Markup class can be used for three different things: When passed an unicode object it’s assumed to be safe, when passed an object with an HTML representation (has an __html__ method) that representation is used, otherwise the object passed is converted into a unicode string and then assumed to be safe:

>>> Markup("Hello <em>World</em>!")
Markup(u'Hello <em>World</em>!')
>>> class Foo(object):
...  def __html__(self):
...   return '<a href="#">foo</a>'
... 
>>> Markup(Foo())
Markup(u'<a href="#">foo</a>')

If you want object passed being always treated as unsafe you can use the escape() classmethod to create a Markup object:

>>> Markup.escape("Hello <em>World</em>!")
Markup(u'Hello &lt;em&gt;World&lt;/em&gt;!')

Operations on a markup string are markup aware which means that all arguments are passed through the escape() function:

>>> em = Markup("<em>%s</em>")
>>> em % "foo & bar"
Markup(u'<em>foo &amp; bar</em>')
>>> strong = Markup("<strong>%(text)s</strong>")
>>> strong % {'text': '<blink>hacker here</blink>'}
Markup(u'<strong>&lt;blink&gt;hacker here&lt;/blink&gt;</strong>')
>>> Markup("<em>Hello</em> ") + "<foo>"
Markup(u'<em>Hello</em> &lt;foo&gt;')

Methods

capitalize(() -> unicode) Return a capitalized version of S, i.e. make the first character
center((width[, fillchar]) -> unicode) Return S centered in a Unicode string of length width. Padding is
count((sub[, start[, end]]) -> int) Return the number of non-overlapping occurrences of substring sub in
decode(...) Decodes S using the codec registered for encoding. encoding defaults
encode(...) Encodes S using the codec registered for encoding. encoding defaults
endswith((suffix[, start[, end]]) -> bool) Return True if S ends with the specified suffix, False otherwise.
escape(s) Escape the string.
expandtabs(([tabsize]) -> unicode) Return a copy of S where all tab characters are expanded using spaces.
find((sub [,start [,end]]) -> int) Return the lowest index in S where substring sub is found,
format((*args, **kwargs) -> unicode) Return a formatted version of S, using substitutions from args and kwargs.
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
isalpha(() -> bool) Return True if all characters in S are alphabetic
isdecimal(() -> bool) Return True if there are only decimal characters in S,
isdigit(() -> bool) Return True if all characters in S are digits
islower(() -> bool) Return True if all cased characters in S are lowercase and there is
isnumeric(() -> bool) Return True if there are only numeric characters in S,
isspace(() -> bool) Return True if all characters in S are whitespace
istitle(() -> bool) Return True if S is a titlecased string and there is at least one
isupper(() -> bool) Return True if all cased characters in S are uppercase and there is
join((iterable) -> unicode) Return a string which is the concatenation of the strings in the iterable.
ljust((width[, fillchar]) -> int) Return S left-justified in a Unicode string of length width. Padding is
lower(() -> unicode) Return a copy of the string S converted to lowercase.
lstrip(([chars]) -> unicode) Return a copy of the string S with leading whitespace removed.
replace((old, new[, count]) -> unicode) Return a copy of S with all occurrences of substring
rfind((sub [,start [,end]]) -> int) Return the highest index in S where substring sub is found,
rindex((sub [,start [,end]]) -> int) Like S.rfind() but raise ValueError when the substring is not found.
rjust((width[, fillchar]) -> unicode) Return S right-justified in a Unicode string of length width. Padding is
rpartition(sep) -> (head, sep, tail) Search for the separator sep in S, starting at the end of S, and return
rsplit(([sep [,maxsplit]]) -> list of strings) Return a list of the words in S, using sep as the
rstrip(([chars]) -> unicode) Return a copy of the string S with trailing whitespace removed.
split(([sep [,maxsplit]]) -> list of strings) Return a list of the words in S, using sep as the
splitlines(([keepends]) -> list of strings) Return a list of the lines in S, breaking at line boundaries.
startswith((prefix[, start[, end]]) -> bool) Return True if S starts with the specified prefix, False otherwise.
strip(([chars]) -> unicode) Return a copy of the string S with leading and trailing
striptags() Unescape markup into an unicode string and strip all tags.
swapcase(() -> unicode) Return a copy of S with uppercase characters converted to lowercase
title(() -> unicode) Return a titlecased version of S, i.e. words start with title case
translate((table) -> unicode) Return a copy of the string S, where all characters have been mapped
unescape() Unescape markup again into an unicode string.
upper(() -> unicode) Return a copy of S converted to uppercase.
zfill((width) -> unicode) Pad a numeric string S with zeros on the left, to fill a field

Attributes

partition tuple() -> empty tuple

Descriptions

class Markup

Method details

capitalize() → unicode

Return a capitalized version of S, i.e. make the first character have upper case and the rest lower case.

center(width[, fillchar]) → unicode

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

classmethod escape(s)

Escape the string. Works like escape() with the difference that for subclasses of Markup this function would return the correct subclass.

expandtabs([tabsize]) → unicode

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.

format(*args, **kwargs) → unicode

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

join(iterable) → unicode

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

ljust(width[, fillchar]) → int

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

lower() → unicode

Return a copy of the string S converted to lowercase.

lstrip([chars]) → 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 a str, it will be converted to unicode before stripping

replace(old, new[, count]) → unicode

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

rjust(width[, fillchar]) → unicode

Return S right-justified in a Unicode 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 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, any whitespace string is a separator.

rstrip([chars]) → 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 a str, it will be converted to unicode before stripping

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

Return a list of the words in 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.

strip([chars]) → 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 a str, it will be converted to unicode before stripping

striptags()

Unescape markup into an unicode string and strip all tags. This also resolves known HTML4 and XHTML entities. Whitespace is normalized to one:

>>> Markup("Main &raquo;  <em>About</em>").striptags()
u'Main \xbb About'
swapcase() → unicode

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

title() → unicode

Return a titlecased version of S, i.e. words start with title case characters, all remaining cased characters have lower case.

translate(table) → unicode

Return a copy of the string S, where all characters have been mapped through the given translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, Unicode strings or None. Unmapped characters are left untouched. Characters mapped to None are deleted.

unescape()

Unescape markup again into an unicode string. This also resolves known HTML4 and XHTML entities:

>>> Markup("Main &raquo; <em>About</em>").unescape()
u'Main \xbb <em>About</em>'
upper() → unicode

Return a copy of S converted to uppercase.

zfill(width) → unicode

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

Attribute details

partition = (<function partition at 0x026D3730>,)

Inherited member details

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

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

decode([encoding[, errors]]) → string or unicode

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 registerd with codecs.register_error that is able to handle UnicodeDecodeErrors.

encode([encoding[, errors]]) → string or unicode

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 can 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.

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.

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.

isdecimal() → bool

Return True if there are only decimal characters 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.

isnumeric() → bool

Return True if there are only numeric characters 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. upper- and titlecase 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.

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.

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.

Table Of Contents

Previous topic

suite

Next topic

jinja2._stringdefs