diff --git a/Doc/library/stdtypes.rst b/Doc/library/stdtypes.rst index 2952c50787ad5d..03a3dff248b5cb 100644 --- a/Doc/library/stdtypes.rst +++ b/Doc/library/stdtypes.rst @@ -1579,13 +1579,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 @@ -1595,7 +1603,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:: + + >>> 'ß'.casefold() + 'ss' + >>> 'ß'.lower() + 'ß' The casefolding algorithm is described in section 3.13 of the Unicode Standard. @@ -1607,16 +1620,30 @@ 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]]) Return the number of non-overlapping occurrences of substring *sub* in the range [*start*, *end*]. Optional arguments *start* and *end* are - interpreted as in slice notation. + interpreted as in slice notation. 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 .. method:: str.encode(encoding="utf-8", errors="strict") @@ -1634,6 +1661,14 @@ expression support in the :mod:`re` module). Mode `, or use a :ref:`debug build ` to check *errors*. + For example:: + + >>> encoded_str_to_byte = 'Python'.encode() + >>> type(encoded_str_to_byte) + + >>> encoded_str_to_byte + b'Python' + .. versionchanged:: 3.1 Support for keyword arguments added. @@ -1647,8 +1682,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`. .. method:: str.expandtabs(tabsize=8) @@ -1669,13 +1715,25 @@ expression support in the :mod:`re` module). '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`. .. note:: @@ -1739,6 +1797,15 @@ expression support in the :mod:`re` module). Like :meth:`~str.find`, but raise :exc:`ValueError` when the substring is 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() @@ -1747,6 +1814,16 @@ expression support in the :mod:`re` module). of the following returns ``True``: ``c.isalpha()``, ``c.isdecimal()``, ``c.isdigit()``, or ``c.isnumeric()``. + For example:: + + >>> ''.isalnum() + False + >>> 'abc123'.isalnum() + True + >>> 'abc123!@#'.isalnum() + False + >>> ' '.isalnum() + False .. method:: str.isalpha() @@ -1756,6 +1833,20 @@ 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 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() @@ -1763,6 +1854,19 @@ expression support in the :mod:`re` module). ``False`` otherwise. 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 @@ -1775,6 +1879,16 @@ expression support in the :mod:`re` module). ZERO. Formally a decimal character is a character in the Unicode 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() @@ -1785,14 +1899,24 @@ 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. + 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() Return ``True`` if the string is a valid identifier according to the language definition, section :ref:`identifiers`. - Call :func:`keyword.iskeyword` to test whether string ``s`` is a reserved - identifier, such as :keyword:`def` and :keyword:`class`. + You can to call :func:`keyword.iskeyword` to test whether string ``s`` is a + reserved identifier, such as :keyword:`def` and :keyword:`class`. Example: :: @@ -1810,6 +1934,20 @@ 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. + For example:: + + >>> 'BANANA'.islower() + False + >>> 'banana'.islower() + True + >>> 'baNana'.islower() + False + >>> ' '.islower() + False + >>> ''.islower() + False + + See also :meth:`isupper`. .. method:: str.isnumeric() @@ -1820,6 +1958,20 @@ 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. + 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() @@ -1831,6 +1983,18 @@ 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`.) + 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() @@ -1842,6 +2006,18 @@ expression support in the :mod:`re` module). ("Separator, space"), or its bidirectional class is one of ``WS``, ``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() @@ -1849,6 +2025,16 @@ 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. + For example:: + + >>> 'Spam, Spam, Spam'.istitle() + True + >>> 'spam, spam, spam'.istitle() + False + >>> 'SPAM, SPAM, SPAM'.istitle() + False + + See also :meth:`title`. .. method:: str.isupper() @@ -1863,8 +2049,10 @@ expression support in the :mod:`re` module). False >>> ' '.isupper() False + >>> ''.isupper() + False - + See also :meth:`islower`. .. _meth-str-join: @@ -1875,6 +2063,13 @@ expression support in the :mod:`re` module). *iterable*, including :class:`bytes` objects. The separator between 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]) @@ -1882,15 +2077,27 @@ 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)``. + 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 of the Unicode Standard. + See also :meth:`casefold`, :meth:`swapcase` and :meth:`upper`. .. method:: str.lstrip([chars]) @@ -1912,6 +2119,7 @@ expression support in the :mod:`re` module). >>> 'Arthur: three!'.removeprefix('Arthur: ') 'three!' + See also :meth:`rstrip`. .. staticmethod:: str.maketrans(x[, y[, z]]) @@ -1922,11 +2130,20 @@ expression support in the :mod:`re` module). strings (of arbitrary lengths) or ``None``. Character keys will then be 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) @@ -1935,6 +2152,14 @@ 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. + For example:: + + >>> 'Monty Python'.partition(' ') + ('Monty', ' ', 'Python') + >>> 'Monty Python'.partition('-') + ('Monty Python', '', '') + + See also :meth:`rpartition` .. method:: str.removeprefix(prefix, /) @@ -1970,6 +2195,12 @@ expression support in the :mod:`re` module). *new*. If the optional argument *count* is given, only the first *count* occurrences are replaced. + For example:: + + >>> 'spam, spam, spam'.replace('spam', 'eggs') + 'eggs, eggs, eggs' + >>> 'spam, spam, spam'.replace('spam', 'eggs', 1) + 'eggs, spam, spam' .. method:: str.rfind(sub[, start[, end]]) @@ -1977,12 +2208,28 @@ 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. + 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. + 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]) @@ -1990,6 +2237,14 @@ 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)``. + For example:: + + >>> 'Python'.rjust(10) + ' Python' + >>> 'Python'.rjust(10, '.') + '....Python' + + See also :meth:`ljust`. .. method:: str.rpartition(sep) @@ -1998,6 +2253,12 @@ 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. + For example:: + + >>> "Monty Python's Flying Circus".rpartition(' ') + ("Monty Python's Flying", ' ', 'Circus') + + See also :meth:`partition`. .. method:: str.rsplit(sep=None, maxsplit=-1) @@ -2007,6 +2268,10 @@ 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. + For example:: + + >>> '1,2,3'.rsplit(',', maxsplit=1) + ['1,2', '3'] .. method:: str.rstrip([chars]) @@ -2028,6 +2293,8 @@ expression support in the :mod:`re` module). >>> '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 @@ -2067,6 +2334,7 @@ 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 @@ -2141,6 +2409,18 @@ expression support in the :mod:`re` module). test string beginning at that position. With optional *end*, stop comparing 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`. .. method:: str.strip([chars]) @@ -2172,6 +2452,12 @@ expression support in the :mod:`re` module). vice versa. Note that it is not necessarily true that ``s.swapcase().swapcase() == s``. + For example:: + + >>> 'Monty Python'.swapcase() + 'mONTY pYTHON' + + See also :meth:`upper` and :meth:`lower`. .. method:: str.title() @@ -2206,6 +2492,7 @@ 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) @@ -2221,6 +2508,13 @@ expression support in the :mod:`re` module). You can use :meth:`str.maketrans` to create a translation map from 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. @@ -2233,9 +2527,17 @@ expression support in the :mod:`re` module). character(s) is not "Lu" (Letter, uppercase), but e.g. "Lt" (Letter, titlecase). + For example:: + + >>> 'Monty Python'.upper() + 'MONTY PYTHON' + >>> '𐊠'.upper().isupper() # 'CARIAN LETTER A' + False + The uppercasing algorithm used is described in section 3.13 of the Unicode Standard. + See also :meth:`swapcase` and :meth:`lower`. .. method:: str.zfill(width)