7.1. string — Common string operations¶
Source code: Lib/string.py
The string module contains a number of useful constants and
classes, as well as some deprecated legacy functions that are also
available as methods on strings. In addition, Python’s built-in string
classes support the sequence type methods described in the
Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrange section, and also the string-specific methods described
in the String Methods section. To output formatted strings use
template strings or the % operator described in the
String Formatting Operations section. Also, see the re module for
string functions based on regular expressions.
7.1.1. String constants¶
The constants defined in this module are:
-
string.ascii_letters¶ The concatenation of the
ascii_lowercaseandascii_uppercaseconstants described below. This value is not locale-dependent.
-
string.ascii_lowercase¶ The lowercase letters
'abcdefghijklmnopqrstuvwxyz'. This value is not locale-dependent and will not change.
-
string.ascii_uppercase¶ The uppercase letters
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. This value is not locale-dependent and will not change.
-
string.digits¶ The string
'0123456789'.
-
string.hexdigits¶ The string
'0123456789abcdefABCDEF'.
-
string.letters¶ The concatenation of the strings
lowercaseanduppercasedescribed below. The specific value is locale-dependent, and will be updated whenlocale.setlocale()is called.
-
string.lowercase¶ A string containing all the characters that are considered lowercase letters. On most systems this is the string
'abcdefghijklmnopqrstuvwxyz'. The specific value is locale-dependent, and will be updated whenlocale.setlocale()is called.
-
string.octdigits¶ The string
'01234567'.
-
string.punctuation¶ String of ASCII characters which are considered punctuation characters in the
Clocale.
-
string.printable¶ String of characters which are considered printable. This is a combination of
digits,letters,punctuation, andwhitespace.
-
string.uppercase¶ A string containing all the characters that are considered uppercase letters. On most systems this is the string
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. The specific value is locale-dependent, and will be updated whenlocale.setlocale()is called.
-
string.whitespace¶ A string containing all characters that are considered whitespace. On most systems this includes the characters space, tab, linefeed, return, formfeed, and vertical tab.
7.1.2. Custom String Formatting¶
New in version 2.6.
The built-in str and unicode classes provide the ability
to do complex variable substitutions and value formatting via the
str.format() method described in PEP 3101. The Formatter
class in the string module allows you to create and customize your own
string formatting behaviors using the same implementation as the built-in
format() method.
-
class
string.Formatter¶ The
Formatterclass has the following public methods:-
format(format_string, *args, **kwargs)¶ The primary API method. It takes a format string and an arbitrary set of positional and keyword arguments. It is just a wrapper that calls
vformat().
-
vformat(format_string, args, kwargs)¶ This function does the actual work of formatting. It is exposed as a separate function for cases where you want to pass in a predefined dictionary of arguments, rather than unpacking and repacking the dictionary as individual arguments using the
*argsand**kwargssyntax.vformat()does the work of breaking up the format string into character data and replacement fields. It calls the various methods described below.
In addition, the
Formatterdefines a number of methods that are intended to be replaced by subclasses:-
parse(format_string)¶ Loop over the format_string and return an iterable of tuples (literal_text, field_name, format_spec, conversion). This is used by
vformat()to break the string into either literal text, or replacement fields.The values in the tuple conceptually represent a span of literal text followed by a single replacement field. If there is no literal text (which can happen if two replacement fields occur consecutively), then literal_text will be a zero-length string. If there is no replacement field, then the values of field_name, format_spec and conversion will be
None.
-
get_field(field_name, args, kwargs)¶ Given field_name as returned by
parse()(see above), convert it to an object to be formatted. Returns a tuple (obj, used_key). The default version takes strings of the form defined in PEP 3101, such as “0[name]” or “label.title”. args and kwargs are as passed in tovformat(). The return value used_key has the same meaning as the key parameter toget_value().
-
get_value(key, args, kwargs)¶ Retrieve a given field value. The key argument will be either an integer or a string. If it is an integer, it represents the index of the positional argument in args; if it is a string, then it represents a named argument in kwargs.
The args parameter is set to the list of positional arguments to
vformat(), and the kwargs parameter is set to the dictionary of keyword arguments.For compound field names, these functions are only called for the first component of the field name; Subsequent components are handled through normal attribute and indexing operations.
So for example, the field expression ‘0.name’ would cause
get_value()to be called with a key argument of 0. Thenameattribute will be looked up afterget_value()returns by calling the built-ingetattr()function.If the index or keyword refers to an item that does not exist, then an
IndexErrororKeyErrorshould be raised.
-
check_unused_args(used_args, args, kwargs)¶ Implement checking for unused arguments if desired. The arguments to this function is the set of all argument keys that were actually referred to in the format string (integers for positional arguments, and strings for named arguments), and a reference to the args and kwargs that was passed to vformat. The set of unused args can be calculated from these parameters.
check_unused_args()is assumed to raise an exception if the check fails.
-
format_field(value, format_spec)¶ format_field()simply calls the globalformat()built-in. The method is provided so that subclasses can override it.
-
convert_field(value, conversion)¶ Converts the value (returned by
get_field()) given a conversion type (as in the tuple returned by theparse()method). The default version understands ‘s’ (str), ‘r’ (repr) and ‘a’ (ascii) conversion types.
-
7.1.3. Format String Syntax¶
The str.format() method and the Formatter class share the same
syntax for format strings (although in the case of Formatter,
subclasses can define their own format string syntax).
Format strings contain “replacement fields” surrounded by curly braces {}.
Anything that is not contained in braces is considered literal text, which is
copied unchanged to the output. If you need to include a brace character in the
literal text, it can be escaped by doubling: {{ and }}.
The grammar for a replacement field is as follows:
replacement_field ::= "{" [field_name] ["!"conversion] [":"format_spec] "}" field_name ::= arg_name ("."attribute_name| "["element_index"]")* arg_name ::= [identifier|integer] attribute_name ::=identifierelement_index ::=integer|index_stringindex_string ::= <any source character except "]"> + conversion ::= "r" | "s" format_spec ::= <described in the next section>
In less formal terms, the replacement field can start with a field_name that specifies
the object whose value is to be formatted and inserted
into the output instead of the replacement field.
The field_name is optionally followed by a conversion field, which is
preceded by an exclamation point '!', and a format_spec, which is preceded
by a colon ':'. These specify a non-default format for the replacement value.
See also the Format Specification Mini-Language section.
The field_name itself begins with an arg_name that is either a number or a
keyword. If it’s a number, it refers to a positional argument, and if it’s a keyword,
it refers to a named keyword argument. If the numerical arg_names in a format string
are 0, 1, 2, … in sequence, they can all be omitted (not just some)
and the numbers 0, 1, 2, … will be automatically inserted in that order.
Because arg_name is not quote-delimited, it is not possible to specify arbitrary
dictionary keys (e.g., the strings '10' or ':-]') within a format string.
The arg_name can be followed by any number of index or
attribute expressions. An expression of the form '.name' selects the named
attribute using getattr(), while an expression of the form '[index]'
does an index lookup using __getitem__().
Changed in version 2.7: The positional argument specifiers can be omitted for str.format() and
unicode.format(), so '{} {}' is equivalent to '{0} {1}',
u'{} {}' is equivalent to u'{0} {1}'.
Some simple format string examples:
"First, thou shalt count to {0}" # References first positional argument
"Bring me a {}" # Implicitly references the first positional argument
"From {} to {}" # Same as "From {0} to {1}"
"My quest is {name}" # References keyword argument 'name'
"Weight in tons {0.weight}" # 'weight' attribute of first positional arg
"Units destroyed: {players[0]}" # First element of keyword argument 'players'.
The conversion field causes a type coercion before formatting. Normally, the
job of formatting a value is done by the __format__() method of the value
itself. However, in some cases it is desirable to force a type to be formatted
as a string, overriding its own definition of formatting. By converting the
value to a string before calling __format__(), the normal formatting logic
is bypassed.
Two conversion flags are currently supported: '!s' which calls str()
on the value, and '!r' which calls repr().
Some examples:
"Harold's a clever {0!s}" # Calls str() on the argument first
"Bring out the holy {name!r}" # Calls repr() on the argument first
The format_spec field contains a specification of how the value should be presented, including such details as field width, alignment, padding, decimal precision and so on. Each value type can define its own “formatting mini-language” or interpretation of the format_spec.
Most built-in types support a common formatting mini-language, which is described in the next section.
A format_spec field can also include nested replacement fields within it. These nested replacement fields may contain a field name, conversion flag and format specification, but deeper nesting is not allowed. The replacement fields within the format_spec are substituted before the format_spec string is interpreted. This allows the formatting of a value to be dynamically specified.
See the Format examples section for some examples.
7.1.3.1. Format Specification Mini-Language¶
“Format specifications” are used within replacement fields contained within a
format string to define how individual values are presented (see
Format String Syntax). They can also be passed directly to the built-in
format() function. Each formattable type may define how the format
specification is to be interpreted.
Most built-in types implement the following options for format specifications, although some of the formatting options are only supported by the numeric types.
A general convention is that an empty format string ("") produces
the same result as if you had called str() on the value. A
non-empty format string typically modifies the result.
The general form of a standard format specifier is:
format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type] fill ::= <any character> align ::= "<" | ">" | "=" | "^" sign ::= "+" | "-" | " " width ::=integerprecision ::=integertype ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
If a valid align value is specified, it can be preceded by a fill
character that can be any character and defaults to a space if omitted.
It is not possible to use a literal curly brace (“{” or “}”) as
the fill character when using the str.format()
method. However, it is possible to insert a curly brace
with a nested replacement field. This limitation doesn’t
affect the format() function.
The meaning of the various alignment options is as follows:
Option
Meaning
'<'Forces the field to be left-aligned within the available space (this is the default for most objects).
'>'Forces the field to be right-aligned within the available space (this is the default for numbers).
'='Forces the padding to be placed after the sign (if any) but before the digits. This is used for printing fields in the form ‘+000000120’. This alignment option is only valid for numeric types. It becomes the default when ‘0’ immediately precedes the field width.
'^'Forces the field to be centered within the available space.
Note that unless a minimum field width is defined, the field width will always be the same size as the data to fill it, so that the alignment option has no meaning in this case.
The sign option is only valid for number types, and can be one of the following:
Option
Meaning
'+'indicates that a sign should be used for both positive as well as negative numbers.
'-'indicates that a sign should be used only for negative numbers (this is the default behavior).
space
indicates that a leading space should be used on positive numbers, and a minus sign on negative numbers.
The '#' option is only valid for integers, and only for binary, octal, or
hexadecimal output. If present, it specifies that the output will be prefixed
by '0b', '0o', or '0x', respectively.
The ',' option signals the use of a comma for a thousands separator.
For a locale aware separator, use the 'n' integer presentation type
instead.
Changed in version 2.7: Added the ',' option (see also PEP 378).
width is a decimal integer defining the minimum field width. If not specified, then the field width will be determined by the content.
When no explicit alignment is given, preceding the width field by a zero
('0') character enables
sign-aware zero-padding for numeric types. This is equivalent to a fill
character of '0' with an alignment type of '='.
The precision is a decimal number indicating how many digits should be
displayed after the decimal point for a floating point value formatted with
'f' and 'F', or before and after the decimal point for a floating point
value formatted with 'g' or 'G'. For non-number types the field
indicates the maximum field size - in other words, how many characters will be
used from the field content. The
