diff --git a/Doc/library/stdtypes.rst b/Doc/library/stdtypes.rst index 652ed147af8422..c591cbbe86d90a 100644 --- a/Doc/library/stdtypes.rst +++ b/Doc/library/stdtypes.rst @@ -1621,13 +1621,21 @@ expression support in the :mod:`re` module). .. method:: str.capitalize() Return a copy of the string with its first character capitalized and the - rest lowercased. + rest lowercased. For example:: + + >>> 'PYTHON IS AMAZING'.capitalize() + 'Python is amazing' + >>> 'Njemačka Starts With a non-english Digraph'.capitalize() + 'Njemačka starts with a non-english digraph' + + See also :meth:`title`. .. versionchanged:: 3.8 The first character is now put into titlecase rather than uppercase. This means that characters like digraphs will only have their first letter capitalized, instead of the full character. + .. method:: str.casefold() Return a casefolded copy of the string. Casefolded strings may be used for @@ -1637,7 +1645,12 @@ expression support in the :mod:`re` module). intended to remove all case distinctions in a string. For example, the German lowercase letter ``'ß'`` is equivalent to ``"ss"``. Since it is already lowercase, :meth:`lower` would do nothing to ``'ß'``; :meth:`casefold` - converts it to ``"ss"``. + converts it to ``"ss"``, as follows. For example:: + + >>> 'ß'.casefold() + 'ss' + >>> 'ß'.lower() + 'ß' The casefolding algorithm is `described in section 3.13 'Default Case Folding' of the Unicode Standard @@ -1650,8 +1663,14 @@ expression support in the :mod:`re` module). Return centered in a string of length *width*. Padding is done using the specified *fillchar* (default is an ASCII space). The original string is - returned if *width* is less than or equal to ``len(s)``. + returned if *width* is less than or equal to ``len(s)``. For example:: + >>> 'Python'.center(10) + ' Python ' + >>> 'Python'.center(10, '-') + '--Python--' + >>> 'Python'.center(4) + 'Python' .. method:: str.count(sub[, start[, end]]) @@ -1661,7 +1680,18 @@ expression support in the :mod:`re` module). interpreted as in slice notation. If *sub* is empty, returns the number of empty strings between characters - which is the length of the string plus one. + which is the length of the string plus one. For example:: + + >>> 'spam, spam, spam'.count('spam') + 3 + >>> 'spam, spam, spam'.count('spam', 5) + 2 + >>> 'spam, spam, spam'.count('spam', 5, 10) + 1 + >>> 'spam, spam, spam'.count('eggs') + 0 + >>> 'spam, spam, spam'.count('') + 17 .. method:: str.encode(encoding="utf-8", errors="strict") @@ -1681,7 +1711,13 @@ expression support in the :mod:`re` module). For performance reasons, the value of *errors* is not checked for validity unless an encoding error actually occurs, :ref:`devmode` is enabled - or a :ref:`debug build ` is used. + or a :ref:`debug build ` is used. For example:: + + >>> encoded_str_to_byte = 'Python'.encode() + >>> type(encoded_str_to_byte) + + >>> encoded_str_to_byte + b'Python' .. versionchanged:: 3.1 Added support for keyword arguments. @@ -1696,7 +1732,19 @@ expression support in the :mod:`re` module). Return ``True`` if the string ends with the specified *suffix*, otherwise return ``False``. *suffix* can also be a tuple of suffixes to look for. With optional *start*, test beginning at that position. With optional *end*, stop comparing - at that position. + at that position. Use the *start* and *end* is equivalent to + ``str[start:end].endswith(suffix)``. For example:: + + >>> 'Python'.endswith('on') + True + >>> 'a tuple of suffixes'.endswith(('at', 'in')) + False + >>> 'a tuple of suffixes'.endswith(('at', 'es')) + True + >>> 'Python is amazing'.endswith('is', 0, 9) + True + + See also :meth:`startswith` and :meth:`removesuffix`. .. method:: str.expandtabs(tabsize=8) @@ -1712,25 +1760,36 @@ expression support in the :mod:`re` module). (``\n``) or return (``\r``), it is copied and the current column is reset to zero. Any other character is copied unchanged and the current column is incremented by one regardless of how the character is represented when - printed. + printed. For example:: >>> '01\t012\t0123\t01234'.expandtabs() '01 012 0123 01234' >>> '01\t012\t0123\t01234'.expandtabs(4) '01 012 0123 01234' + >>> print('01\t012\n0123\t01234'.expandtabs(4)) + 01 012 + 0123 01234 .. method:: str.find(sub[, start[, end]]) Return the lowest index in the string where substring *sub* is found within the slice ``s[start:end]``. Optional arguments *start* and *end* are - interpreted as in slice notation. Return ``-1`` if *sub* is not found. + interpreted as in slice notation. Return ``-1`` if *sub* is not found. For + example:: + + >>> 'spam, spam, spam'.find('sp') + 0 + >>> 'spam, spam, spam'.find('sp', 5) + 6 + + See also :meth:`rfind` and :meth:`index`. .. note:: The :meth:`~str.find` method should be used only if you need to know the position of *sub*. To check if *sub* is a substring or not, use the - :keyword:`in` operator:: + :keyword:`in` operator. For example:: >>> 'Py' in 'Python' True @@ -1743,7 +1802,7 @@ expression support in the :mod:`re` module). ``{}``. Each replacement field contains either the numeric index of a positional argument, or the name of a keyword argument. Returns a copy of the string where each replacement field is replaced with the string value of - the corresponding argument. + the corresponding argument. For example:: >>> "The sum of 1 + 2 is {0}".format(1+2) 'The sum of 1 + 2 is 3' @@ -1771,14 +1830,14 @@ expression support in the :mod:`re` module). Similar to ``str.format(**mapping)``, except that ``mapping`` is used directly and not copied to a :class:`dict`. This is useful - if for example ``mapping`` is a dict subclass: + if for example ``mapping`` is a dict subclass. For example:: - >>> class Default(dict): - ... def __missing__(self, key): - ... return key - ... - >>> '{name} was born in {country}'.format_map(Default(name='Guido')) - 'Guido was born in country' + >>> class Default(dict): + ... def __missing__(self, key): + ... return key + ... + >>> '{name} was born in {country}'.format_map(Default(name='Guido')) + 'Guido was born in country' .. versionadded:: 3.2 @@ -1786,7 +1845,14 @@ expression support in the :mod:`re` module). .. method:: str.index(sub[, start[, end]]) Like :meth:`~str.find`, but raise :exc:`ValueError` when the substring is - not found. + not found. For example:: + + >>> 'spam, spam, spam'.index('eggs') + Traceback (most recent call last): + File "", line 1, in + ValueError: substring not found + + See also :meth:`rindex`. .. method:: str.isalnum() @@ -1794,7 +1860,16 @@ expression support in the :mod:`re` module). Return ``True`` if all characters in the string are alphanumeric and there is at least one character, ``False`` otherwise. A character ``c`` is alphanumeric if one of the following returns ``True``: ``c.isalpha()``, ``c.isdecimal()``, - ``c.isdigit()``, or ``c.isnumeric()``. + ``c.isdigit()``, or ``c.isnumeric()``. For example:: + + >>> ''.isalnum() + False + >>> 'abc123'.isalnum() + True + >>> 'abc123!@#'.isalnum() + False + >>> ' '.isalnum() + False .. method:: str.isalpha() @@ -1805,14 +1880,38 @@ expression support in the :mod:`re` module). property being one of "Lm", "Lt", "Lu", "Ll", or "Lo". Note that this is different from the `Alphabetic property defined in the section 4.10 'Letters, Alphabetic, and Ideographic' of the Unicode Standard - `_. + `_. For example:: + + >>> 'a commom word'.isalpha() + False + >>> 'acommomword'.isalpha() + True + >>> 'µ'.isalpha() + True + >>> 'æ'.isalpha() + True + >>> 'Ŧ'.isalpha() + True + + See Unicode Properties section in :ref:`unicode-howto`. .. method:: str.isascii() Return ``True`` if the string is empty or all characters in the string are ASCII, ``False`` otherwise. - ASCII characters have code points in the range U+0000-U+007F. + ASCII characters have code points in the range U+0000-U+007F. For example:: + + >>> 'a commom word'.isascii() + True + >>> 'acommomword'.isascii() + True + >>> 'µ'.isascii() + False + >>> 'æ'.isascii() + False + >>> 'Ŧ'.isascii() + False .. versionadded:: 3.7 @@ -1824,7 +1923,16 @@ expression support in the :mod:`re` module). otherwise. Decimal characters are those that can be used to form numbers in base 10, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. Formally a decimal character is a character in the Unicode - General Category "Nd". + General Category "Nd". For example:: + + >>> '0123456789'.isdecimal() + True + >>> '٠١٢٣٤٥٦٧٨٩'.isdecimal() # ARABIC-INDIC DIGIT ZERO TO NINE + True + >>> '²'.isdecimal(), '²'.isdigit() + (False, True) + + See also :meth:`isdigit`. Decimal numbers is a digit numbers subset. .. method:: str.isdigit() @@ -1834,7 +1942,16 @@ expression support in the :mod:`re` module). special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the Kharosthi numbers. Formally, a digit is a character that has the - property value Numeric_Type=Digit or Numeric_Type=Decimal. + property value Numeric_Type=Digit or Numeric_Type=Decimal. For example:: + + >>> '0123456789'.isdigit() + True + >>> '٠١٢٣٤٥٦٧٨٩'.isdigit() # ARABIC-INDIC DIGIT ZERO TO NINE + True + >>> '²'.isdigit(), '²'.isdecimal() + (True, False) + + See also :meth:`isdecimal`. Digit numbers is a decimal numbers superset. .. method:: str.isidentifier() @@ -1843,10 +1960,7 @@ expression support in the :mod:`re` module). definition, section :ref:`identifiers`. :func:`keyword.iskeyword` can be used to test whether string ``s`` is a reserved - identifier, such as :keyword:`def` and :keyword:`class`. - - Example: - :: + identifier, such as :keyword:`def` and :keyword:`class`. For example:: >>> from keyword import iskeyword @@ -1859,7 +1973,20 @@ expression support in the :mod:`re` module). .. method:: str.islower() Return ``True`` if all cased characters [4]_ in the string are lowercase and - there is at least one cased character, ``False`` otherwise. + there is at least one cased character, ``False`` otherwise. For example:: + + >>> 'BANANA'.islower() + False + >>> 'banana'.islower() + True + >>> 'baNana'.islower() + False + >>> ' '.islower() + False + >>> ''.islower() + False + + See also :meth:`isupper`. .. method:: str.isnumeric() @@ -1869,7 +1996,19 @@ expression support in the :mod:`re` module). otherwise. Numeric characters include digit characters, and all characters that have the Unicode numeric value property, e.g. U+2155, VULGAR FRACTION ONE FIFTH. Formally, numeric characters are those with the property - value Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numeric. + value Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numeric. For example:: + + >>> '0123456789'.isnumeric() + True + >>> '٠١٢٣٤٥٦٧٨٩'.isnumeric() # ARABIC-INDIC DIGIT ZERO TO NINE + True + >>> '⅕'.isnumeric() # VULGAR FRACTION ONE FIFTH + True + >>> '²'.isdigit(), '²'.isdecimal(), '²'.isnumeric() + (True, False, True) + + See also :meth:`isdecimal` and :meth:`isdigit`. Numeric characters is a + decimal numbers superset. .. method:: str.isprintable() @@ -1880,7 +2019,18 @@ expression support in the :mod:`re` module). ASCII space (0x20) which is considered printable. (Note that printable characters in this context are those which should not be escaped when :func:`repr` is invoked on a string. It has no bearing on the handling of - strings written to :data:`sys.stdout` or :data:`sys.stderr`.) + strings written to :data:`sys.stdout` or :data:`sys.stderr`.) For example:: + + >>> ''.isprintable() + True + >>> ' '.isprintable() + True + >>> '\t\n'.isprintable() # TAB and BREAK LINE + False + >>> '\u3000'.isprintable() # IDEOGRAPHIC SPACE + False + + See also :meth:`isspace`. .. method:: str.isspace() @@ -1891,20 +2041,41 @@ expression support in the :mod:`re` module). A character is *whitespace* if in the Unicode character database (see :mod:`unicodedata`), either its general category is ``Zs`` ("Separator, space"), or its bidirectional class is one of ``WS``, - ``B``, or ``S``. + ``B``, or ``S``. For example:: + + >>> ''.isspace() + False + >>> ' '.isspace() + True + >>> '\t\n'.isspace() # TAB and BREAK LINE + True + >>> '\u3000'.isspace() # IDEOGRAPHIC SPACE + True + + See also :meth:`isprintable`. .. method:: str.istitle() Return ``True`` if the string is a titlecased string and there is at least one character, for example uppercase characters may only follow uncased characters - and lowercase characters only cased ones. Return ``False`` otherwise. + and lowercase characters only cased ones. Return ``False`` otherwise. For + example:: + + >>> 'Spam, Spam, Spam'.istitle() + True + >>> 'spam, spam, spam'.istitle() + False + >>> 'SPAM, SPAM, SPAM'.istitle() + False + + See also :meth:`title`. .. method:: str.isupper() Return ``True`` if all cased characters [4]_ in the string are uppercase and - there is at least one cased character, ``False`` otherwise. + there is at least one cased character, ``False`` otherwise. For example:: >>> 'BANANA'.isupper() True @@ -1914,7 +2085,10 @@ expression support in the :mod:`re` module). False >>> ' '.isupper() False + >>> ''.isupper() + False + See also :meth:`islower`. .. _meth-str-join: @@ -1924,7 +2098,12 @@ expression support in the :mod:`re` module). Return a string which is the concatenation of the strings in *iterable*. A :exc:`TypeError` will be raised if there are any non-string values in *iterable*, including :class:`bytes` objects. The separator between - elements is the string providing this method. + elements is the string providing this method. For example:: + + >>> ', '.join(['spam', 'spam', 'spam']) + 'spam, spam, spam' + >>> '-'.join('Python') + 'P-y-t-h-o-n' .. method:: str.ljust(width[, fillchar]) @@ -1932,12 +2111,23 @@ expression support in the :mod:`re` module). Return the string left justified in a string of length *width*. Padding is done using the specified *fillchar* (default is an ASCII space). The original string is returned if *width* is less than or equal to ``len(s)``. + For example:: + + >>> 'Python'.ljust(10) + 'Python ' + >>> 'Python'.ljust(10, '.') + 'Python....' + + See also :meth:`rjust`. .. method:: str.lower() Return a copy of the string with all the cased characters [4]_ converted to - lowercase. + lowercase. For example:: + + >>> 'Lower Method Example'.lower() + 'lower method example' The lowercasing algorithm used is `described in section 3.13 'Default Case Folding' of the Unicode Standard @@ -1949,7 +2139,8 @@ expression support in the :mod:`re` module). Return a copy of the string with leading characters removed. The *chars* argument is a string specifying the set of characters to be removed. If omitted or ``None``, the *chars* argument defaults to removing whitespace. The *chars* - argument is not a prefix; rather, all combinations of its values are stripped:: + argument is not a prefix; rather, all combinations of its values are stripped. + For example:: >>> ' spacious '.lstrip() 'spacious ' @@ -1964,6 +2155,8 @@ expression support in the :mod:`re` module). >>> 'Arthur: three!'.removeprefix('Arthur: ') 'three!' + See also :meth:`rstrip`. + .. staticmethod:: str.maketrans(x[, y[, z]]) @@ -1972,12 +2165,19 @@ expression support in the :mod:`re` module). If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters (strings of length 1) to Unicode ordinals, strings (of arbitrary lengths) or ``None``. Character keys will then be - converted to ordinals. + converted to ordinals. For example:: + + >>> str.maketrans({'a': 'A', 'b': 'Boo', 'c': None}) + {97: 'A', 98: 'Boo', 99: None} If there are two arguments, they must be strings of equal length, and in the - resulting dictionary, each character in x will be mapped to the character at - the same position in y. If there is a third argument, it must be a string, - whose characters will be mapped to ``None`` in the result. + resulting dictionary, each character in *x* will be mapped to the character + at the same position in *y*. If there is a third argument, it must be a + string, whose characters will be mapped to ``None`` in the result. For + example:: + + >>> str.maketrans('ab', 'AB', 'c') + {97: 65, 98: 66, 99: None} .. method:: str.partition(sep) @@ -1985,14 +2185,21 @@ expression support in the :mod:`re` module). Split the string at the first occurrence of *sep*, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing - the string itself, followed by two empty strings. + the string itself, followed by two empty strings. For example:: + + >>> 'Monty Python'.partition(' ') + ('Monty', ' ', 'Python') + >>> 'Monty Python'.partition('-') + ('Monty Python', '', '') + + See also :meth:`rpartition`. .. method:: str.removeprefix(prefix, /) If the string starts with the *prefix* string, return ``string[len(prefix):]``. Otherwise, return a copy of the original - string:: + string. For example:: >>> 'TestHook'.removeprefix('Test') 'Hook' @@ -2006,7 +2213,7 @@ expression support in the :mod:`re` module). If the string ends with the *suffix* string and that *suffix* is not empty, return ``string[:-len(suffix)]``. Otherwise, return a copy of the - original string:: + original string. For example:: >>> 'MiscTests'.removesuffix('Tests') 'Misc' @@ -2021,6 +2228,12 @@ expression support in the :mod:`re` module). Return a copy of the string with all occurrences of substring *old* replaced by *new*. If *count* is given, only the first *count* occurrences are replaced. If *count* is not specified or ``-1``, then all occurrences are replaced. + For example:: + + >>> 'spam, spam, spam'.replace('spam', 'eggs') + 'eggs, eggs, eggs' + >>> 'spam, spam, spam'.replace('spam', 'eggs', 1) + 'eggs, spam, spam' .. versionchanged:: 3.13 *count* is now supported as a keyword argument. @@ -2031,12 +2244,27 @@ expression support in the :mod:`re` module). Return the highest index in the string 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. + For example:: + + >>> 'spam, spam, spam'.rfind('sp') + 12 + >>> 'spam, spam, spam'.rfind('sp', 0, 10) + 6 + + See also :meth:`find`. .. method:: str.rindex(sub[, start[, end]]) Like :meth:`rfind` but raises :exc:`ValueError` when the substring *sub* is not - found. + found. For example:: + + >>> 'spam, spam, spam'.rindex('eggs') + Traceback (most recent call last): + File "", line 1, in + ValueError: substring not found + + See also :meth:`index`. .. method:: str.rjust(width[, fillchar]) @@ -2044,6 +2272,14 @@ expression support in the :mod:`re` module). Return the string right justified in a string of length *width*. Padding is done using the specified *fillchar* (default is an ASCII space). The original string is returned if *width* is less than or equal to ``len(s)``. + For example:: + + >>> 'Python'.rjust(10) + ' Python' + >>> 'Python'.rjust(10, '.') + '....Python' + + See also :meth:`ljust`. .. method:: str.rpartition(sep) @@ -2051,7 +2287,12 @@ expression support in the :mod:`re` module). Split the string at the last occurrence of *sep*, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing - two empty strings, followed by the string itself. + two empty strings, followed by the string itself. For example:: + + >>> "Monty Python's Flying Circus".rpartition(' ') + ("Monty Python's Flying", ' ', 'Circus') + + See also :meth:`partition`. .. method:: str.rsplit(sep=None, maxsplit=-1) @@ -2060,7 +2301,10 @@ expression support in the :mod:`re` module). If *maxsplit* is given, at most *maxsplit* splits are done, the *rightmost* ones. If *sep* is not specified or ``None``, any whitespace string is a separator. Except for splitting from the right, :meth:`rsplit` behaves like - :meth:`split` which is described in detail below. + :meth:`split` which is described in detail below. For example:: + + >>> '1,2,3'.rsplit(',', maxsplit=1) + ['1,2', '3'] .. method:: str.rstrip([chars]) @@ -2068,7 +2312,8 @@ expression support in the :mod:`re` module). Return a copy of the string with trailing characters removed. The *chars* argument is a string specifying the set of characters to be removed. If omitted or ``None``, the *chars* argument defaults to removing whitespace. The *chars* - argument is not a suffix; rather, all combinations of its values are stripped:: + argument is not a suffix; rather, all combinations of its values are stripped. + For example:: >>> ' spacious '.rstrip() ' spacious' @@ -2076,13 +2321,16 @@ expression support in the :mod:`re` module). 'mississ' See :meth:`str.removesuffix` for a method that will remove a single suffix - string rather than all of a set of characters. For example:: + string rather than all of a set of characters. For example:: >>> 'Monty Python'.rstrip(' Python') 'M' >>> 'Monty Python'.removesuffix(' Python') 'Monty' + See also :meth:`lstrip`. + + .. method:: str.split(sep=None, maxsplit=-1) Return a list of the words in the string, using *sep* as the delimiter @@ -2096,7 +2344,6 @@ expression support in the :mod:`re` module). ``['1', '', '2']``). The *sep* argument may consist of multiple characters (for example, ``'1<>2<>3'.split('<>')`` returns ``['1', '2', '3']``). Splitting an empty string with a specified separator returns ``['']``. - For example:: >>> '1,2,3'.split(',') @@ -2111,9 +2358,7 @@ expression support in the :mod:`re` module). and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a ``None`` separator - returns ``[]``. - - For example:: + returns ``[]``. For example:: >>> '1 2 3'.split() ['1', '2', '3'] @@ -2122,6 +2367,8 @@ expression support in the :mod:`re` module). >>> ' 1 2 3 '.split() ['1', '2', '3'] + See also :meth:`rsplit`. + .. index:: single: universal newlines; str.splitlines method @@ -2194,7 +2441,18 @@ expression support in the :mod:`re` module). Return ``True`` if string starts with the *prefix*, otherwise return ``False``. *prefix* can also be a tuple of prefixes to look for. With optional *start*, test string beginning at that position. With optional *end*, stop comparing - string at that position. + string at that position. For example:: + + >>> 'Python'.startswith('Py') + True + >>> 'a tuple of prefixes'.startswith(('at', 'in')) + False + >>> 'a tuple of suffixes'.startswith(('at', 'a')) + True + >>> 'Python is amazing'.startswith('is', 7) + True + + See also :meth:`endswith` and :meth:`removeprefix`. .. method:: str.strip([chars]) @@ -2203,7 +2461,7 @@ expression support in the :mod:`re` module). The *chars* argument is a string specifying the set of characters to be removed. If omitted or ``None``, the *chars* argument defaults to removing whitespace. The *chars* argument is not a prefix or suffix; rather, all combinations of its - values are stripped:: + values are stripped. For example:: >>> ' spacious '.strip() 'spacious' @@ -2225,15 +2483,18 @@ expression support in the :mod:`re` module). Return a copy of the string with uppercase characters converted to lowercase and vice versa. Note that it is not necessarily true that - ``s.swapcase().swapcase() == s``. + ``s.swapcase().swapcase() == s``. For example:: + + >>> 'Monty Python'.swapcase() + 'mONTY pYTHON' + + See also :meth:`upper` and :meth:`lower`. .. method:: str.title() Return a titlecased version of the string where words start with an uppercase - character and the remaining characters are lowercase. - - For example:: + character and the remaining characters are lowercase. For example:: >>> 'Hello world'.title() 'Hello World' @@ -2241,7 +2502,7 @@ expression support in the :mod:`re` module). The algorithm uses a simple language-independent definition of a word as groups of consecutive letters. The definition works in many contexts but it means that apostrophes in contractions and possessives form word - boundaries, which may not be the desired result:: + boundaries, which may not be the desired result. For example:: >>> "they're bill's friends from the UK".title() "They'Re Bill'S Friends From The Uk" @@ -2250,7 +2511,7 @@ expression support in the :mod:`re` module). splits words on spaces only. Alternatively, a workaround for apostrophes can be constructed using regular - expressions:: + expressions. For example:: >>> import re >>> def titlecase(s): @@ -2261,6 +2522,8 @@ expression support in the :mod:`re` module). >>> titlecase("they're bill's friends.") "They're Bill's Friends." + See also :meth:`istitle`. + .. method:: str.translate(table) @@ -2274,7 +2537,12 @@ expression support in the :mod:`re` module). :exc:`LookupError` exception, to map the character to itself. You can use :meth:`str.maketrans` to create a translation map from - character-to-character mappings in different formats. + character-to-character mappings in different formats. For example:: + + >>> str.maketrans('to', '70') + {116: 55, 111: 48} + >>> 'Python'.translate({116:55, 111:48}) + 'Py7h0n' See also the :mod:`codecs` module for a more flexible approach to custom character mappings. @@ -2286,12 +2554,19 @@ expression support in the :mod:`re` module). uppercase. Note that ``s.upper().isupper()`` might be ``False`` if ``s`` contains uncased characters or if the Unicode category of the resulting character(s) is not "Lu" (Letter, uppercase), but e.g. "Lt" (Letter, - titlecase). + titlecase). For example:: + + >>> 'Monty Python'.upper() + 'MONTY PYTHON' + >>> '𐊠'.upper().isupper() # 'CARIAN LETTER A' + False The uppercasing algorithm used is `described in section 3.13 'Default Case Folding' of the Unicode Standard `__. + See also :meth:`swapcase` and :meth:`lower`. + .. method:: str.zfill(width) @@ -2299,9 +2574,7 @@ expression support in the :mod:`re` module). make a string of length *width*. A leading sign prefix (``'+'``/``'-'``) is handled by inserting the padding *after* the sign character rather than before. The original string is returned if *width* is less than - or equal to ``len(s)``. - - For example:: + or equal to ``len(s)``. For example:: >>> "42".zfill(5) '00042' @@ -2309,7 +2582,6 @@ expression support in the :mod:`re` module). '-0042' - .. _old-string-formatting: ``printf``-style String Formatting