Thestring module contains a number of useful constants and classes, aswell as some deprecated legacy functions that are also available as methods onstrings. In addition, Python’s built-in string classes support the sequence typemethods described in theSequence Types — str, bytes, bytearray, list, tuple, range section, and also the string-specificmethods described in theString Methods section. To output formattedstrings, see theString Formatting section. Also, see theremodule for string functions based on regular expressions.
The constants defined in this module are:
The built-in string class provides the ability to do complex variablesubstitutions and value formatting via theformat() method described inPEP 3101. TheFormatter class in thestring module allowsyou to create and customize your own string formatting behaviors using the sameimplementation as the built-informat() method.
TheFormatter class has the following public methods:
In addition, theFormatter defines a number of methods that areintended to be replaced by subclasses:
Loop over the format_string and return an iterable of tuples(literal_text,field_name,format_spec,conversion). This is usedbyvformat() to break the string in to either literal text, orreplacement fields.
The values in the tuple conceptually represent a span of literal textfollowed by a single replacement field. If there is no literal text(which can happen if two replacement fields occur consecutively), thenliteral_text will be a zero-length string. If there is no replacementfield, then the values offield_name,format_spec andconversionwill beNone.
Retrieve a given field value. Thekey argument will be either aninteger or a string. If it is an integer, it represents the index of thepositional argument inargs; if it is a string, then it represents anamed argument inkwargs.
Theargs parameter is set to the list of positional arguments tovformat(), and thekwargs parameter is set to the dictionary ofkeyword arguments.
For compound field names, these functions are only called for the firstcomponent of the field name; Subsequent components are handled throughnormal attribute and indexing operations.
So for example, the field expression ‘0.name’ would causeget_value() to be called with akey argument of 0. Thenameattribute will be looked up afterget_value() returns by calling thebuilt-ingetattr() function.
If the index or keyword refers to an item that does not exist, then anIndexError orKeyError should be raised.
Thestr.format() method and theFormatter class share the samesyntax for format strings (although in the case ofFormatter,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 iscopied unchanged to the output. If you need to include a brace character in theliteral 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 ::= (identifier |integer) ("."attribute_name | "[" element_index "]")*attribute_name ::=identifierelement_index ::=integerconversion ::= "r" | "s" | "a"format_spec ::= <described in the next section>
In less formal terms, the replacement field starts with afield_name, whichcan either be a number (for a positional argument), or an identifier (forkeyword arguments). Following this is an optionalconversion field, which ispreceded by an exclamation point'!', and aformat_spec, which is precededby a colon':'.
Thefield_name itself begins with either a number or a keyword. If it’s anumber, it refers to a positional argument, and if it’s a keyword it refers to anamed keyword argument. This can be followed by any number of index orattribute expressions. An expression of the form'.name' selects the namedattribute usinggetattr(), while an expression of the form'[index]'does an index lookup using__getitem__().
Some simple format string examples:
"First, thou shalt count to {0}"# References first positional argument"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'.
Theconversion field causes a type coercion before formatting. Normally, thejob of formatting a value is done by the__format__() method of the valueitself. However, in some cases it is desirable to force a type to be formattedas a string, overriding its own definition of formatting. By converting thevalue to a string before calling__format__(), the normal formatting logicis bypassed.
Three conversion flags are currently supported:'!s' which callsstr()on the value,'!r' which callsrepr() and'!a' which callsascii().
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
Theformat_spec field contains a specification of how the value should bepresented, including such details as field width, alignment, padding, decimalprecision and so on. Each value type can define it’s own “formattingmini-language” or interpretation of theformat_spec.
Most built-in types support a common formatting mini-language, which isdescribed in the next section.
Aformat_spec field can also include nested replacement fields within it.These nested replacement fields can contain only a field name; conversion flagsand format specifications are not allowed. The replacement fields within theformat_spec are substituted before theformat_spec string is interpreted.This allows the formatting of a value to be dynamically specified.
For example, suppose you wanted to have a replacement field whose field width isdetermined by another variable:
"A man with two {0:{1}}".format("noses",10)
This would first evaluate the inner replacement field, making the format stringeffectively:
"A man with two {0:10}"
Then the outer replacement field would be evaluated, producing:
"noses "
Which is substituted into the string, yielding:
"A man with two noses "
(The extra space is because we specified a field width of 10, and because leftalignment is the default for strings.)
“Format specifications” are used within replacement fields contained within aformat string to define how individual values are presented (seeFormat String Syntax.) They can also be passed directly to the builtinformat() function. Each formattable type may define how the formatspecification 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 sameresult as if you had calledstr() on the value.
The general form of astandard format specifier is:
format_spec ::= [[fill]align][sign][#][0][width][.precision][type]fill ::= <a character other than '}'>align ::= "<" | ">" | "=" | "^"sign ::= "+" | "-" | " "width ::=integerprecision ::=integertype ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "x" | "X" | "%"
Thefill character can be any character other than ‘}’ (which signifies theend of the field). The presence of a fill character is signaled by thenextcharacter, which must be one of the alignment options. If the second characterofformat_spec is not a valid alignment option, then it is assumed that boththe fill character and the alignment option are absent.
The meaning of the various alignment options is as follows:
Option Meaning '<' Forces the field to be left-aligned within the availablespace (This is the default.) '>' Forces the field to be right-aligned within theavailable space. '=' Forces the padding to be placed after the sign (if any)but before the digits. This is used for printing fieldsin the form ‘+000000120’. This alignment option is onlyvalid for numeric types. '^' Forces the field to be centered within the availablespace.
Note that unless a minimum field width is defined, the field width will alwaysbe the same size as the data to fill it, so that the alignment option has nomeaning in this case.
Thesign option is only valid for number types, and can be one of thefollowing:
Option Meaning '+' indicates that a sign should be used for bothpositive as well as negative numbers. '-' indicates that a sign should be used only for negativenumbers (this is the default behavior). space indicates that a leading space should be used onpositive numbers, and a minus sign on negative numbers.
The'#' option is only valid for integers, and only for binary, octal, orhexadecimal output. If present, it specifies that the output will be prefixedby'0b','0o', or'0x', respectively.
width is a decimal integer defining the minimum field width. If notspecified, then the field width will be determined by the content.
If thewidth field is preceded by a zero ('0') character, this enableszero-padding. This is equivalent to analignment type of'=' and afillcharacter of'0'.
Theprecision is a decimal number indicating how many digits should bedisplayed after the decimal point for a floating point value formatted with'f' and'F', or before and after the decimal point for a floating pointvalue formatted with'g' or'G'. For non-number types the fieldindicates the maximum field size - in other words, how many characters will beused from the field content. Theprecision is ignored for integer values.
Finally, thetype determines how the data should be presented.
The available integer presentation types are:
Type Meaning 'b' Binary format. Outputs the number in base 2. 'c' Character. Converts the integer to the correspondingunicode character before printing. 'd' Decimal Integer. Outputs the number in base 10. 'o' Octal format. Outputs the number in base 8. 'x' Hex format. Outputs the number in base 16, using lower-case letters for the digits above 9. 'X' Hex format. Outputs the number in base 16, using upper-case letters for the digits above 9. 'n' Number. This is the same as'd', except that it usesthe current locale setting to insert the appropriatenumber separator characters. None The same as'd'.
The available presentation types for floating point and decimal values are:
Type Meaning 'e' Exponent notation. Prints the number in scientificnotation using the letter ‘e’ to indicate the exponent. 'E' Exponent notation. Same as'e' except it uses anupper case ‘E’ as the separator character. 'f' Fixed point. Displays the number as a fixed-pointnumber. 'F' Fixed point. Same as'f'. 'g' General format. This prints the number as a fixed-pointnumber, unless the number is too large, in which caseit switches to'e' exponent notation. Infinity andNaN values are formatted asinf,-inf andnan, respectively. 'G' General format. Same as'g' except switches to'E' if the number gets to large. The representationsof infinity and NaN are uppercased, too. 'n' Number. This is the same as'g', except that it usesthe current locale setting to insert the appropriatenumber separator characters. '%' Percentage. Multiplies the number by 100 and displaysin fixed ('f') format, followed by a percent sign. None The same as'g'.
Templates provide simpler string substitutions as described inPEP 292.Instead of the normal%-based substitutions, Templates support$-based substitutions, using the following rules:
Any other appearance of$ in the string will result in aValueErrorbeing raised.
Thestring module provides aTemplate class that implementsthese rules. The methods ofTemplate are:
The constructor takes a single argument which is the template string.
Likesubstitute(), except that if placeholders are missing frommapping andkws, instead of raising aKeyError exception, theoriginal placeholder will appear in the resulting string intact. Also,unlike withsubstitute(), any other appearances of the$ willsimply return$ instead of raisingValueError.
While other exceptions may still occur, this method is called “safe”because substitutions always tries to return a usable string instead ofraising an exception. In another sense,safe_substitute() may beanything other than safe, since it will silently ignore malformedtemplates containing dangling delimiters, unmatched braces, orplaceholders that are not valid Python identifiers.
Template instances also provide one public data attribute:
Here is an example of how to use a Template:
>>> from string import Template>>> s = Template('$who likes $what')>>> s.substitute(who='tim', what='kung pao')'tim likes kung pao'>>> d = dict(who='tim')>>> Template('Give $who $100').substitute(d)Traceback (most recent call last):[...]ValueError: Invalid placeholder in string: line 1, col 10>>> Template('$who likes $what').substitute(d)Traceback (most recent call last):[...]KeyError: 'what'>>> Template('$who likes $what').safe_substitute(d)'tim likes $what'
Advanced usage: you can derive subclasses ofTemplate to customize theplaceholder syntax, delimiter character, or the entire regular expression usedto parse template strings. To do this, you can override these class attributes:
Alternatively, you can provide the entire regular expression pattern byoverriding the class attributepattern. If you do this, the value must be aregular expression object with four named capturing groups. The capturinggroups correspond to the rules given above, along with the invalid placeholderrule:
The following functions are available to operate on string objects.They are not available as string methods.
re — Regular expression operations
Enter search terms or a module, class or function name.