In [9]:
# imports
import string

string module is different form string type(str)

this notebook will focus on string module, the similarity and difference will be highlighted when necensary.


In [10]:
print(type('ass'))
print(type(string))


<class 'str'>
<class 'module'>

string

string constants


In [11]:
string.ascii_letters


Out[11]:
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

In [12]:
string.punctuation


Out[12]:
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

string.Formater

The Formatter class implements the same layout specification language as the format() method of str. Its features include type coersion, alignment, attribute and field references, named and positional template arguments, and type-specific formatting options. Most of the time the format() method is a more convenient interface to these features, but Formatter is provided as a way to build subclasses, for cases where variations are needed.

str format

This is very similar to old styple 'printf', with the addition of the {} support


In [13]:
'{0} {1} {2}'.format('a','b','c')


Out[13]:
'a b c'

string Tempalte

instead of normal %-based substitution, Tempaltes support $-based sustitutions, using the following rule:

  • $$ is an escapte, replace single $.

  • identifier names a sustitution placeholder matching a mapping key of 'identifer.

  • ${identifier} is equivalent to $identifier. It is required when valid identifier characters follow the placeholder but are not part of the placeholder, such as "${noun}ification".

In [14]:
from string import Template

In [15]:
s = Template('$who likes $what')

In [16]:
s.substitute(who='tim', what='kung pao')


Out[16]:
'tim likes kung pao'

string Helper functions


In [7]:
string.capwords("hello string")


Out[7]:
'Hello String'