6.1. string

: Lib/string.py


6.1.1.

:

string.ascii_letters

ascii_lowercase ascii_uppercase

string.ascii_lowercase

'abcdefghijklmnopqrstuvwxyz'

string.ascii_uppercase

'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

string.digits

'0123456789'

string.hexdigits

'0123456789abcdefABCDEF'

string.octdigits

'01234567'

string.punctuation

C ASCII

string.printable

ASCII digits, ascii_letters, punctuation whitespace

string.whitespace

(whitespace) ASCII (space) (tab) (linefeed) (return) (formfeed) (vertical tab)

6.1.2.

(string) PEP 3101 format() string Formatter format()

class string.Formatter

Formatter :

format(format_string, *args, **kwargs)

API vformat()

3.5 : format_string

vformat(format_string, args, kwargs)

*args **kwargs unpack pack vformat()

Formatter

parse(format_string)

format_string (literal_text, field_name, format_spec, conversion) vformat()

() literal_text 0 field_name, format_spec conversion None

get_field(field_name, args, kwargs)

parse() () field_name (obj, used_key) PEP 3101 "0[name]" "label.title" args kwargs vformat() used_key get_value() key

get_value(key, args, kwargs)

key args kwargs

args vformat() kwargs

;

'0.name' get_value() key 0 name getattr() get_value()

IndexError KeyError

check_unused_args(used_args, args, kwargs)

set () vformat args kwargs set check_unused_args()

format_field(value, format_spec)

format_field() format()

convert_field(value, conversion)

(get_field() ) (parse() ) 's' (str), 'r' (repr), 'a' (ascii)

6.1.3.

str.format() Formatter ( Formatter )

{} "" : {{ }}

:

replacement_field ::=  "{" [field_name] ["!" conversion] [":" format_spec] "}"
field_name        ::=  arg_name ("." attribute_name | "[" element_index "]")*
arg_name          ::=  [identifier | digit+]
attribute_name    ::=  identifier
element_index     ::=  digit+ | index_string
index_string      ::=  <any source character except "]"> +
conversion        ::=  "r" | "s" | "a"
format_spec       ::=  <described in the next section>

field_name field_name '!' conversion ':' format_spec

field_name arg_name arg_names 0, 1, 2, () 0, 1, 2, arg_name ( '10' ':-]' ) arg_name '.name' getattr() '[index]' __getitem__()

3.1 : The positional argument specifiers can be omitted, so '{} {}' is equivalent to '{0} {1}'.

:

"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'.

(conversion) __format__() __format__()

3: str() '!s' repr() '!r' ascii() '!a'

:

"Harold's a clever {0!s}"        # Calls str() on the argument first
"Bring out the holy {name!r}"    # Calls repr() on the argument first
"More {!a}"                      # Calls ascii() on the argument first

format_spec "formatting mini-language" format_spec

formatting mini-language

format_spec format_spec format_spec

6.1.3.1.

("Format specifications") ( ) format()

("") str()

(standard format specifier) :

format_spec     ::=  [[fill]align][sign][#][0][width][grouping_option][.precision][type]
fill            ::=  <any character>
align           ::=  "<" | ">" | "=" | "^"
sign            ::=  "+" | "-" | " "
width           ::=  digit+
grouping_option ::=  "_" | ","
precision       ::=  digit+
type            ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

align fill formatted string literal str.format() ("{" "}") fill format()

align :

'<' ()
'>' ()
'=' () '+000000120' '0'
'^'

align

sign :

'+'
'-' ()

'#' 102816 '0b', '0o', '0x' 10'g' 'G' 0

',' 'n'

3.1 : ',' (PEP 378 )

'_' 'd' 'b', 'o', 'x', 'X' 4

3.6 : '_' (PEP 515 )

width 10

alignment width ('0') 0 fill '0' alignment '='

precision 10'f' 'F' 'g' 'G' precision

type

:

's'
None 's'

:

'b' 22
'c' Unicode
'd' 1010
'o' 88
'x' 1616 109
'X' 1616 109
'n' 'd'
None 'd'

('n' None ) float()

10:

'e' 'e' 6
'E' 'E' 'e'
'f' 6
'F' nan NAN inf INF 'f'
'g'

p >= 1 p

: 'e' p-1 exp -4 <= exp < p 'f' p-1-exp 'e' p-1 0 ,

0 NaN inf, -inf, 0, -0 nan

0 1 6

'G' 'E' 'g' NaN
'n' 'g'
'%' 100 ('f')
None 'g' 1 str()

6.1.3.2.

str.format() %-

{} % : %-'%03.2f' '{:03.2f}'

:

>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'
>>> '{}, {}, {}'.format('a', 'b', 'c')  # 3.1+ only
'a, b, c'
>>> '{2}, {1}, {0}'.format('a', 'b', 'c')
'c, b, a'
>>> '{2}, {1}, {0}'.format(*'abc')      # unpacking argument sequence
'c, b, a'
>>> '{0}{1}{0}'.format('abra', 'cad')   # arguments' indices can be repeated
'abracadabra'

:

>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
'Coordinates: 37.24N, -115.81W'

:

>>> c = 3-5j
>>> ('The complex number {0} is formed from the real part {0.real} '
...  'and the imaginary part {0.imag}.').format(c)
'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'
>>> class Point:
...     def __init__(self, x, y):
...         self.x, self.y = x, y
...     def __str__(self):
...         return 'Point({self.x}, {self.y})'.format(self=self)
...
>>> str(Point(4, 2))
'Point(4, 2)'

:

>>> coord = (3, 5)
>>> 'X: {0[0]};  Y: {0[1]}'.format(coord)
'X: 3;  Y: 5'

%s %r :

>>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
"repr() shows quotes: 'test1'; str() doesn't: test2"

:

>>> '{:<30}'.format('left aligned')
'left aligned                  '
>>> '{:>30}'.format('right aligned')
'                 right aligned'
>>> '{:^30}'.format('centered')
'           centered           '
>>> '{:*^30}'.format('centered')  # use '*' as a fill char
'***********centered***********'

%+f %-f, % f :

>>> '{:+f}; {:+f}'.format(3.14, -3.14)  # show it always
'+3.140000; -3.140000'
>>> '{: f}; {: f}'.format(3.14, -3.14)  # show a space for positive numbers
' 3.140000; -3.140000'
>>> '{:-f}; {:-f}'.format(3.14, -3.14)  # show only the minus -- same as '{:f}; {:f}'
'3.140000; -3.140000'

%x %o :

>>> # format also supports binary numbers
>>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)
'int: 42;  hex: 2a;  oct: 52;  bin: 101010'
>>> # with 0x, 0o, or 0b as prefix:
>>> "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)
'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010'

:

>>> '{:,}'.format(1234567890)
'1,234,567,890'

:

>>> points = 19
>>> total = 22
>>> 'Correct answers: {:.2%}'.format(points/total)
'Correct answers: 86.36%'

:

>>> import datetime
>>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
>>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
'2010-07-04 12:15:58'

:

>>> for align, text in zip('<^>', ['left', 'center', 'right']):
...     '{0:{fill}{align}16}'.format(text, fill=align, align=align)
...
'left<<<<<<<<<<<<'
'^^^^^center^^^^^'
'>>>>>>>>>>>right'
>>>
>>> octets = [192, 168, 0, 1]
>>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets)
'C0A80001'
>>> int(_, 16)
3232235521
>>>
>>> width = 5
>>> for num in range(5,12): 
...     for base in 'dXob':
...         print('{0:{width}{base}}'.format(num, base=base, width=width), end=' ')
...     print()
...
    5     5     5   101
    6     6     6   110
    7     7     7   111
    8     8    10  1000
    9     9    11  1001
   10     A    12  1010
   11     B    13  1011

6.1.4.

(template) PEP 292 (string substitution) % $ :

  • $$ ; $
  • $identifier "identifier" "identifier" ASCII () ASCII $
  • ${identifier} $identifier "${noun}ification"

$ ValueError

string Template Template :

class string.Template(template)

substitute(mapping, **kwds)

mapping mapping kwds kwds

safe_substitute(mapping, **kwds)

substitute() mapping kwds KeyError substitute() $ ValueError $

(safe) safe_substitute() (dangling delimiter) Python

Template public :

template

template

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 11
>>> Template('$who likes $what').substitute(d)
Traceback (most recent call last):
...
KeyError: 'what'
>>> Template('$who likes $what').safe_substitute(d)
'tim likes $what'

: Template :

  • delimiter $ re.escape()

  • idpattern () (?-i:[_a-zA-Z][_a-zA-Z0-9]*)

    flags re.IGNORECASE [a-z] ASCII -i

    flags re.IGNORECASE 0 re.IGNORECASE | re.ASCII

  • flags re.IGNORECASE re.VERBOSE idpattern verbose

    3.2 .

pattern pattern 4 (capturing group) :

  • escaped $$
  • named ;
  • braced ;
  • invalid ()

6.1.5.

string.capwords(s, sep=None)

str.split() str.capitalize() str.join() 2 sep None sep split join