Movatterモバイル変換


[0]ホーム

URL:


Navigation

string — Common string operations

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.

String constants

The constants defined in this module are:

string.ascii_letters
The concatenation of theascii_lowercase andascii_uppercaseconstants described below. This value is not locale-dependent.
string.ascii_lowercase
The lowercase letters'abcdefghijklmnopqrstuvwxyz'. This value is notlocale-dependent and will not change.
string.ascii_uppercase
The uppercase letters'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. This value is notlocale-dependent and will not change.
string.digits
The string'0123456789'.
string.hexdigits
The string'0123456789abcdefABCDEF'.
string.octdigits
The string'01234567'.
string.punctuation
String of ASCII characters which are considered punctuation charactersin theC locale.
string.printable
String of ASCII characters which are considered printable. This is acombination ofdigits,ascii_letters,punctuation,andwhitespace.
string.whitespace
A string containing all ASCII characters that are considered whitespace.This includes the characters space, tab, linefeed, return, formfeed, andvertical tab.

String Formatting

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.

classstring.Formatter

TheFormatter class has the following public methods:

format(format_string,*args,*kwargs)
format() is the primary API method. It takes a format templatestring, and an arbitrary set of positional and keyword argument.format() is just a wrapper that callsvformat().
vformat(format_string,args,kwargs)
This function does the actual work of formatting. It is exposed as aseparate function for cases where you want to pass in a predefineddictionary of arguments, rather than unpacking and repacking thedictionary as individual arguments using the*args and**kwdssyntax.vformat() does the work of breaking up the format templatestring into character data and replacement fields. It calls the variousmethods described below.

In addition, theFormatter defines a number of methods that areintended 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 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.

get_field(field_name,args,kwargs)
Givenfield_name as returned byparse() (see above), convert it toan object to be formatted. Returns a tuple (obj, used_key). The defaultversion takes strings of the form defined inPEP 3101, such as“0[name]” or “label.title”.args andkwargs are as passed in tovformat(). The return valueused_key has the same meaning as thekey parameter toget_value().
get_value(key,args,kwargs)

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.

check_unused_args(used_args,args,kwargs)
Implement checking for unused arguments if desired. The arguments to thisfunction is the set of all argument keys that were actually referred to inthe format string (integers for positional arguments, and strings fornamed arguments), and a reference to theargs andkwargs that waspassed to vformat. The set of unused args can be calculated from theseparameters.check_unused_args() is assumed to throw an exception ifthe check fails.
format_field(value,format_spec)
format_field() simply calls the globalformat() built-in. Themethod is provided so that subclasses can override it.
convert_field(value,conversion)
Converts the value (returned byget_field()) given a conversion type(as in the tuple returned by theparse() method.) The defaultversion understands ‘r’ (repr) and ‘s’ (str) conversion types.

Format String Syntax

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 Specification Mini-Language

“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:

OptionMeaning
'<'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:

OptionMeaning
'+'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).
spaceindicates 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:

TypeMeaning
'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.
NoneThe same as'd'.

The available presentation types for floating point and decimal values are:

TypeMeaning
'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.
NoneThe same as'g'.

Template strings

Templates provide simpler string substitutions as described inPEP 292.Instead of the normal%-based substitutions, Templates support$-based substitutions, using the following rules:

  • $$ is an escape; it is replaced with a single$.
  • $identifier names a substitution placeholder matching a mapping key of"identifier". By default,"identifier" must spell a Pythonidentifier. The first non-identifier character after the$ characterterminates this placeholder specification.
  • ${identifier} is equivalent to$identifier. It is required when valididentifier characters follow the placeholder but are not part of theplaceholder, such as"${noun}ification".

Any other appearance of$ in the string will result in aValueErrorbeing raised.

Thestring module provides aTemplate class that implementsthese rules. The methods ofTemplate are:

classstring.Template(template)

The constructor takes a single argument which is the template string.

substitute(mapping[,**kws])
Performs the template substitution, returning a new string.mapping isany dictionary-like object with keys that match the placeholders in thetemplate. Alternatively, you can provide keyword arguments, where thekeywords are the placeholders. When bothmapping andkws are givenand there are duplicates, the placeholders fromkws take precedence.
safe_substitute(mapping[,**kws])

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:

string.template
This is the object passed to the constructor’stemplate argument. In general,you shouldn’t change it, but read-only access is not enforced.

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:

  • delimiter – This is the literal string describing a placeholder introducingdelimiter. The default value$. Note that this shouldnot be a regularexpression, as the implementation will callre.escape() on this string asneeded.
  • idpattern – This is the regular expression describing the pattern fornon-braced placeholders (the braces will be added automatically asappropriate). The default value is the regular expression[_a-z][_a-z0-9]*.

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:

  • escaped – This group matches the escape sequence, e.g.$$, in thedefault pattern.
  • named – This group matches the unbraced placeholder name; it should notinclude the delimiter in capturing group.
  • braced – This group matches the brace enclosed placeholder name; it shouldnot include either the delimiter or braces in the capturing group.
  • invalid – This group matches any other delimiter pattern (usually a singledelimiter), and it should appear last in the regular expression.

String functions

The following functions are available to operate on string objects.They are not available as string methods.

string.capwords(s)
Split the argument into words usingsplit(), capitalize each word usingcapitalize(), and join the capitalized words usingjoin(). Notethat this replaces runs of whitespace characters by a single space, and removesleading and trailing whitespace.
string.maketrans(frm,to)
Return a translation table suitable for passing tobytes.translate(),that will map each character infrom into the character at the sameposition into;from andto must have the same length.

Table Of Contents

Previous topic

String Services

Next topic

re — Regular expression operations

This Page

Quick search

Enter search terms or a module, class or function name.

Navigation

©Copyright 1990-2009, Python Software Foundation. Last updated on Feb 14, 2009. Created usingSphinx 0.6.

[8]ページ先頭

©2009-2025 Movatter.jp