python字符串详解–str

python中的字符串是不可变序列(sequence)

String literals are written in a variety of ways:

三引号字符串可以跨多行。特殊字符也会被计入字符串。

如果两个字符串之间只有空格(或没有空格),会被隐含的合并成一个

ss="abc"'DEF' # 'abcDEF'
ss="abc"  "abc" # 'abcabc'
ss="""ab
cd
ef  g"""    'ab\ncd\nef\tg'

String and Bytes literals

字符串常量?,将其用于字符串引号之前有特殊作用。字符串的默认编码方式是utf-8.

前缀:

格式:replacement_field ::= "{" f_expression ["!" conversion] [":" format_spec] "}"

If a conversion is specified, the result of evaluating the expression is converted before formatting. Conversion ‘!s’ calls str() on the result, ‘!r’ calls repr(), and ‘!a’ calls ascii().

Top-level format specifiers may include nested replacement fields. These nested fields may include their own conversion fields and format specifiers, but may not include more deeply-nested replacement fields.

name="Fred"
f"He said his name is {name!r}."
# "He said his name is 'Fred'."
f"He said his name si {repr(name)}." #repr() is equivalent to !r
width=10
precision=4
value=decimal.Decimal("12.34567")
f"result:{value:{width}.{precision}}" #nested fields
# 'result:     12.35'

索引

由于没有单独的character类型,对字符串的索引返回长度为1的字符串 对于非空字符串:s[0]==s[0:1]

String Methods

字符串格式化

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

# by position
>>> '{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

# by name
'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'

# accessing arguments' attributes
>>> 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)'

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

#Aligning the text and specifying a width:
>>> '{:<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***********'

参考

  1. python官方文档