diff --git a/Doc/library/stdtypes.rst b/Doc/library/stdtypes.rst index 1a4c12590c1018..9699e7c3278bfb 100644 --- a/Doc/library/stdtypes.rst +++ b/Doc/library/stdtypes.rst @@ -1625,11 +1625,29 @@ expression support in the :mod:`re` module). Return a copy of the string with its first character capitalized and the rest lowercased. + 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. +.. raw:: html + +
+
+ See 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' + +.. raw:: html + +
+
+ .. method:: str.casefold() Return a casefolded copy of the string. Casefolded strings may be used for @@ -1647,6 +1665,22 @@ expression support in the :mod:`re` module). .. versionadded:: 3.3 +.. raw:: html + +
+
+ See example + +>>> 'ß'.casefold() +'ss' +>>> 'ß'.lower() +'ß' + +.. raw:: html + +
+
+ .. method:: str.center(width[, fillchar]) @@ -1654,6 +1688,25 @@ expression support in the :mod:`re` module). specified *fillchar* (default is an ASCII space). The original string is returned if *width* is less than or equal to ``len(s)``. +.. raw:: html + +
+
+ See example + +>>> 'Python'.center(10) +' Python ' +>>> 'Python'.center(10, '-') +'--Python--' +>>> 'Python'.center(9) +' Python ' +>>> 'Python'.center(4) +'Python' + +.. raw:: html + +
+
.. method:: str.count(sub[, start[, end]]) @@ -1665,6 +1718,28 @@ expression support in the :mod:`re` module). If *sub* is empty, returns the number of empty strings between characters which is the length of the string plus one. +.. raw:: html + +
+
+ See 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 + +.. raw:: html + +
+
+ .. method:: str.encode(encoding="utf-8", errors="strict") @@ -1681,9 +1756,8 @@ expression support in the :mod:`re` module). See :ref:`error-handlers` for details. 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. + unless an encoding error actually occurs, :ref:`devmode` is enabled or a + :ref:`debug build ` is used. .. versionchanged:: 3.1 Added support for keyword arguments. @@ -1692,13 +1766,53 @@ expression support in the :mod:`re` module). The value of the *errors* argument is now checked in :ref:`devmode` and in :ref:`debug mode `. +.. raw:: html + +
+
+ See example + +>>> encoded_str_to_byte = 'Python'.encode() +>>> type(encoded_str_to_byte) + +>>> encoded_str_to_byte +b'Python' + +.. raw:: html + +
+
+ .. method:: str.endswith(suffix[, start[, end]]) 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 of *start* and *end* is equivalent to + ``str[start:end].endswith(suffix)``. + + See also :meth:`startswith` and :meth:`removesuffix`. + +.. raw:: html + +
+
+ See 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 + +.. raw:: html + +
+
.. method:: str.expandtabs(tabsize=8) @@ -1716,10 +1830,24 @@ expression support in the :mod:`re` module). incremented by one regardless of how the character is represented when printed. - >>> '01\t012\t0123\t01234'.expandtabs() - '01 012 0123 01234' - >>> '01\t012\t0123\t01234'.expandtabs(4) - '01 012 0123 01234' +.. raw:: html + +
+
+ See 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 + +.. raw:: html + +
+
.. method:: str.find(sub[, start[, end]]) @@ -1728,6 +1856,8 @@ expression support in the :mod:`re` module). the slice ``s[start:end]``. Optional arguments *start* and *end* are interpreted as in slice notation. Return ``-1`` if *sub* is not found. + See also :meth:`rfind` and :meth:`index`. + .. note:: The :meth:`~str.find` method should be used only if you need to know the @@ -1737,6 +1867,24 @@ expression support in the :mod:`re` module). >>> 'Py' in 'Python' True +.. raw:: html + +
+
+ See example + +>>> 'spam, spam, spam'.find('sp') +0 +>>> 'spam, spam, spam'.find('sp', 5) +6 +>>> 'spam, spam, spam'.find('eggs') +-1 + +.. raw:: html + +
+
+ .. method:: str.format(*args, **kwargs) @@ -1747,9 +1895,6 @@ expression support in the :mod:`re` module). the string where each replacement field is replaced with the string value of the corresponding argument. - >>> "The sum of 1 + 2 is {0}".format(1+2) - 'The sum of 1 + 2 is 3' - See :ref:`formatstrings` for a description of the various formatting options that can be specified in format strings. @@ -1768,28 +1913,71 @@ expression support in the :mod:`re` module). temporarily the ``LC_CTYPE`` locale to the ``LC_NUMERIC`` locale in some cases. +.. raw:: html + +
+
+ See example + +>>> "The sum of 1 + 2 is {0}".format(1+2) +'The sum of 1 + 2 is 3' + +.. raw:: html + +
+
+ .. method:: str.format_map(mapping) 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: - - >>> class Default(dict): - ... def __missing__(self, key): - ... return key - ... - >>> '{name} was born in {country}'.format_map(Default(name='Guido')) - 'Guido was born in country' + if for example ``mapping`` is a dict subclass. .. versionadded:: 3.2 +.. raw:: html + +
+
+ See 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' + +.. raw:: html + +
+
+ .. method:: str.index(sub[, start[, end]]) Like :meth:`~str.find`, but raise :exc:`ValueError` when the substring is not found. + See also :meth:`rindex`. + + .. raw:: html + +
+
+ See example + + >>> 'spam, spam, spam'.index('eggs') + Traceback (most recent call last): + File "", line 1, in + ValueError: substring not found + + .. raw:: html + +
+
+ .. method:: str.isalnum() @@ -1798,6 +1986,26 @@ expression support in the :mod:`re` module). of the following returns ``True``: ``c.isalpha()``, ``c.isdecimal()``, ``c.isdigit()``, or ``c.isnumeric()``. + .. raw:: html + +
+
+ See example + + >>> ''.isalnum() + False + >>> 'abc123'.isalnum() + True + >>> 'abc123!@#'.isalnum() + False + >>> ' '.isalnum() + False + + .. raw:: html + +
+
+ .. method:: str.isalpha() @@ -1807,7 +2015,31 @@ 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 - `_. + `_. + + See Unicode Properties section in :ref:`unicode-howto`. + + .. raw:: html + +
+
+ See example + + >>> 'a commom word'.isalpha() + False + >>> 'acommomword'.isalpha() + True + >>> 'µ'.isalpha() + True + >>> 'æ'.isalpha() + True + >>> 'Ŧ'.isalpha() + True + + .. raw:: html + +
+
.. method:: str.isascii() @@ -1818,6 +2050,28 @@ expression support in the :mod:`re` module). .. versionadded:: 3.7 + .. raw:: html + +
+
+ See example + + >>> 'a commom word'.isascii() + True + >>> 'acommomword'.isascii() + True + >>> 'µ'.isascii() + False + >>> 'æ'.isascii() + False + >>> 'Ŧ'.isascii() + False + + .. raw:: html + +
+
+ .. method:: str.isdecimal() @@ -1828,6 +2082,26 @@ expression support in the :mod:`re` module). ZERO. Formally a decimal character is a character in the Unicode General Category "Nd". + See also :meth:`isdigit`. Decimal numbers is a digit numbers subset. + + .. raw:: html + +
+
+ See example + + >>> '0123456789'.isdecimal() + True + >>> '٠١٢٣٤٥٦٧٨٩'.isdecimal() # ARABIC-INDIC DIGIT ZERO TO NINE + True + >>> '²'.isdecimal(), '²'.isdigit() + (False, True) + + .. raw:: html + +
+
+ .. method:: str.isdigit() @@ -1838,6 +2112,26 @@ expression support in the :mod:`re` module). like the Kharosthi numbers. Formally, a digit is a character that has the property value Numeric_Type=Digit or Numeric_Type=Decimal. + See also :meth:`isdecimal`. Digit numbers is a decimal numbers superset. + + .. raw:: html + +
+
+ See example + + >>> '0123456789'.isdigit() + True + >>> '٠١٢٣٤٥٦٧٨٩'.isdigit() # ARABIC-INDIC DIGIT ZERO TO NINE + True + >>> '²'.isdigit(), '²'.isdecimal() + (True, False) + + .. raw:: html + +
+
+ .. method:: str.isidentifier() @@ -1847,15 +2141,24 @@ expression support in the :mod:`re` module). :func:`keyword.iskeyword` can be used to test whether string ``s`` is a reserved identifier, such as :keyword:`def` and :keyword:`class`. - Example: - :: + .. raw:: html + +
+
+ See example - >>> from keyword import iskeyword + >>> from keyword import iskeyword + >>> 'hello1'.isidentifier(), iskeyword('hello1') + (True, False) + >>> '1hello'.isidentifier(), iskeyword('1hello') + (False, False) + >>> 'def'.isidentifier(), iskeyword('def') + (True, True) - >>> 'hello'.isidentifier(), iskeyword('hello') - (True, False) - >>> 'def'.isidentifier(), iskeyword('def') - (True, True) + .. raw:: html + +
+
.. method:: str.islower() @@ -1863,6 +2166,30 @@ expression support in the :mod:`re` module). Return ``True`` if all cased characters [4]_ in the string are lowercase and there is at least one cased character, ``False`` otherwise. + See also :meth:`isupper`. + + .. raw:: html + +
+
+ See example + + >>> 'BANANA'.islower() + False + >>> 'banana'.islower() + True + >>> 'baNana'.islower() + False + >>> ' '.islower() + False + >>> ''.islower() + False + + .. raw:: html + +
+
+ .. method:: str.isnumeric() @@ -1873,6 +2200,29 @@ expression support in the :mod:`re` module). VULGAR FRACTION ONE FIFTH. Formally, numeric characters are those with the property value Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numeric. + See also :meth:`isdecimal` and :meth:`isdigit`. Numeric characters is a + decimal numbers superset. + + .. raw:: html + +
+
+ See example + + >>> '0123456789'.isnumeric() + True + >>> '٠١٢٣٤٥٦٧٨٩'.isnumeric() # ARABIC-INDIC DIGIT ZERO TO NINE + True + >>> '⅕'.isnumeric() # VULGAR FRACTION ONE FIFTH + True + >>> '²'.isdigit(), '²'.isdecimal(), '²'.isnumeric() + (True, False, True) + + .. raw:: html + +
+
+ .. method:: str.isprintable() @@ -1884,6 +2234,28 @@ expression support in the :mod:`re` module). :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`.) + See also :meth:`isspace`. + + .. raw:: html + +
+
+ See example + + >>> ''.isprintable() + True + >>> ' '.isprintable() + True + >>> '\t\n'.isprintable() # TAB and BREAK LINE + False + >>> '\u3000'.isprintable() # IDEOGRAPHIC SPACE + False + + .. raw:: html + +
+
+ .. method:: str.isspace() @@ -1895,6 +2267,28 @@ expression support in the :mod:`re` module). ("Separator, space"), or its bidirectional class is one of ``WS``, ``B``, or ``S``. + See also :meth:`isprintable`. + + .. raw:: html + +
+
+ See example + + >>> ''.isspace() + False + >>> ' '.isspace() + True + >>> '\t\n'.isspace() # TAB and BREAK LINE + True + >>> '\u3000'.isspace() # IDEOGRAPHIC SPACE + True + + .. raw:: html + +
+
+ .. method:: str.istitle() @@ -1902,21 +2296,55 @@ expression support in the :mod:`re` module). character, for example uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return ``False`` otherwise. + See also :meth:`title`. + + .. raw:: html + +
+
+ See example + + >>> 'Spam, Spam, Spam'.istitle() + True + >>> 'spam, spam, spam'.istitle() + False + >>> 'SPAM, SPAM, SPAM'.istitle() + False + + .. raw:: html + +
+
+ .. 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. - >>> 'BANANA'.isupper() - True - >>> 'banana'.isupper() - False - >>> 'baNana'.isupper() - False - >>> ' '.isupper() - False + See also :meth:`islower`. + .. raw:: html + +
+
+ See example + + >>> 'BANANA'.isupper() + True + >>> 'banana'.isupper() + False + >>> 'baNana'.isupper() + False + >>> ' '.isupper() + False + >>> ''.isupper() + False + + .. raw:: html + +
+
.. _meth-str-join: @@ -1928,6 +2356,22 @@ expression support in the :mod:`re` module). *iterable*, including :class:`bytes` objects. The separator between elements is the string providing this method. + .. raw:: html + +
+
+ See example + + >>> ', '.join(['spam', 'spam', 'spam']) + 'spam, spam, spam' + >>> '-'.join('Python') + 'P-y-t-h-o-n' + + .. raw:: html + +
+
+ .. method:: str.ljust(width[, fillchar]) @@ -1935,6 +2379,24 @@ expression support in the :mod:`re` module). 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)``. + See also :meth:`rjust`. + + .. raw:: html + +
+
+ See example + + >>> 'Python'.ljust(10) + 'Python ' + >>> 'Python'.ljust(10, '.') + 'Python....' + + .. raw:: html + +
+
+ .. method:: str.lower() @@ -1945,26 +2407,45 @@ expression support in the :mod:`re` module). `described in section 3.13 'Default Case Folding' of the Unicode Standard `__. + .. raw:: html + +
+
+ See example + + >>> 'Lower Method Example'.lower() + 'lower method example' + + .. raw:: html + +
+
.. method:: str.lstrip([chars]) 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. + + See also :meth:`rstrip` and see :meth:`str.removeprefix` for a method that will + remove a single prefix string rather than all of a set of characters. + + .. raw:: html + +
+
+ See example - >>> ' spacious '.lstrip() - 'spacious ' - >>> 'www.example.com'.lstrip('cmowz.') - 'example.com' + >>> ' spacious '.lstrip() + 'spacious ' + >>> 'www.example.com'.lstrip('cmowz.') + 'example.com' - See :meth:`str.removeprefix` for a method that will remove a single prefix - string rather than all of a set of characters. For example:: + .. raw:: html - >>> 'Arthur: three!'.lstrip('Arthur: ') - 'ee!' - >>> 'Arthur: three!'.removeprefix('Arthur: ') - 'three!' +
+
.. staticmethod:: str.maketrans(x[, y[, z]]) @@ -1977,9 +2458,25 @@ expression support in the :mod:`re` module). converted to ordinals. 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. + + .. raw:: html + +
+
+ See example + + >>> str.maketrans({'a': 'A', 'b': 'Boo', 'c': None}) + {97: 'A', 98: 'Boo', 99: None} + >>> str.maketrans('ab', 'AB', 'c') + {97: 65, 98: 66, 99: None} + + .. raw:: html + +
+
.. method:: str.partition(sep) @@ -1989,34 +2486,74 @@ expression support in the :mod:`re` module). after the separator. If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings. + See also :meth:`rpartition`. + + .. raw:: html + +
+
+ See example + + >>> 'Monty Python'.partition(' ') + ('Monty', ' ', 'Python') + >>> 'Monty Python'.partition('-') + ('Monty Python', '', '') + + .. raw:: html + +
+
+ .. method:: str.removeprefix(prefix, /) If the string starts with the *prefix* string, return ``string[len(prefix):]``. Otherwise, return a copy of the original - string:: - - >>> 'TestHook'.removeprefix('Test') - 'Hook' - >>> 'BaseTestCase'.removeprefix('Test') - 'BaseTestCase' + string. .. versionadded:: 3.9 + .. raw:: html + +
+
+ See example + + >>> 'TestHook'.removeprefix('Test') + 'Hook' + >>> 'BaseTestCase'.removeprefix('Test') + 'BaseTestCase' + + .. raw:: html + +
+
+ .. method:: str.removesuffix(suffix, /) 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:: - - >>> 'MiscTests'.removesuffix('Tests') - 'Misc' - >>> 'TmpDirMixin'.removesuffix('Tests') - 'TmpDirMixin' + original string. .. versionadded:: 3.9 + .. raw:: html + +
+
+ See example + + >>> 'MiscTests'.removesuffix('Tests') + 'Misc' + >>> 'TmpDirMixin'.removesuffix('Tests') + 'TmpDirMixin' + + .. raw:: html + +
+
+ .. method:: str.replace(old, new, count=-1) @@ -2027,6 +2564,22 @@ expression support in the :mod:`re` module). .. versionchanged:: 3.13 *count* is now supported as a keyword argument. + .. raw:: html + +
+
+ See example + + >>> 'spam, spam, spam'.replace('spam', 'eggs') + 'eggs, eggs, eggs' + >>> 'spam, spam, spam'.replace('spam', 'eggs', 1) + 'eggs, spam, spam' + + .. raw:: html + +
+
+ .. method:: str.rfind(sub[, start[, end]]) @@ -2034,12 +2587,48 @@ expression support in the :mod:`re` module). that *sub* is contained within ``s[start:end]``. Optional arguments *start* and *end* are interpreted as in slice notation. Return ``-1`` on failure. + See also :meth:`find`. + + .. raw:: html + +
+
+ See example + + >>> 'spam, spam, spam'.rfind('sp') + 12 + >>> 'spam, spam, spam'.rfind('sp', 0, 10) + 6 + + .. raw:: html + +
+
+ .. method:: str.rindex(sub[, start[, end]]) Like :meth:`rfind` but raises :exc:`ValueError` when the substring *sub* is not found. + See also :meth:`index`. + + .. raw:: html + +
+
+ See example + + >>> 'spam, spam, spam'.rindex('eggs') + Traceback (most recent call last): + File "", line 1, in + ValueError: substring not found + + .. raw:: html + +
+
+ .. method:: str.rjust(width[, fillchar]) @@ -2047,6 +2636,24 @@ expression support in the :mod:`re` module). 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)``. + See also :meth:`ljust`. + + .. raw:: html + +
+
+ See example + + >>> 'Python'.rjust(10) + ' Python' + >>> 'Python'.rjust(10, '.') + '....Python' + + .. raw:: html + +
+
+ .. method:: str.rpartition(sep) @@ -2055,6 +2662,22 @@ expression support in the :mod:`re` module). after the separator. If the separator is not found, return a 3-tuple containing two empty strings, followed by the string itself. + See also :meth:`partition`. + + .. raw:: html + +
+
+ See example + + >>> "Monty Python's Flying Circus".rpartition(' ') + ("Monty Python's Flying", ' ', 'Circus') + + .. raw:: html + +
+
+ .. method:: str.rsplit(sep=None, maxsplit=-1) @@ -2064,26 +2687,47 @@ expression support in the :mod:`re` module). separator. Except for splitting from the right, :meth:`rsplit` behaves like :meth:`split` which is described in detail below. + .. raw:: html + +
+
+ See example + + >>> '1,2,3'.rsplit(',', maxsplit=1) + ['1,2', '3'] + + .. raw:: html + +
+
+ .. method:: str.rstrip([chars]) 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. + + See also :meth:`lstrip` and see :meth:`str.removesuffix` for a method that will + remove a single suffix string rather than all of a set of characters. + + .. raw:: html - >>> ' spacious '.rstrip() - ' spacious' - >>> 'mississippi'.rstrip('ipz') - 'mississ' +
+
+ See example - See :meth:`str.removesuffix` for a method that will remove a single suffix - string rather than all of a set of characters. For example:: + >>> ' spacious '.rstrip() + ' spacious' + >>> 'mississippi'.rstrip('ipz') + 'mississ' + + .. raw:: html + +
+
- >>> 'Monty Python'.rstrip(' Python') - 'M' - >>> 'Monty Python'.removesuffix(' Python') - 'Monty' .. method:: str.split(sep=None, maxsplit=-1) @@ -2098,7 +2742,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(',') @@ -2113,9 +2756,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'] @@ -2124,6 +2765,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 @@ -2196,7 +2839,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]) @@ -2205,7 +2859,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' @@ -2227,15 +2881,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' @@ -2243,7 +2900,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" @@ -2252,7 +2909,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): @@ -2263,6 +2920,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) @@ -2276,7 +2935,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. @@ -2288,12 +2952,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) @@ -2301,9 +2972,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' @@ -2311,7 +2980,6 @@ expression support in the :mod:`re` module). '-0042' - .. _old-string-formatting: ``printf``-style String Formatting