[Learning Python] Chapter 7 String Fundamentals

1, 字符串的连接concatenate有两种方式:
A:直接写在一起:

>>> title = "Meaning " 'of' " Life" # Implicit concatenation
>>> title
'Meaning of Life'

B:使用+号

2,raw string: 在string前面加r,就会是string的不再具有转义功能。
应该注意的是,如果str的末尾是, Python仍然会将这个 和它后面的引号转义输出。这时候就不要用raw string了。

3,Triple quotes code multiline block strings: 三个引号(单引号或者双引号)可以做创造多行的strings。此时不要在这里面的右边加入comment,否则会被当做string。

4,triple quotes还可以用来暂时的是某段代码disable。如下面:

X = 1
"""
import os # Disable this code temporarily
print(os.getcwd())
"""
Y = 2

5,字符串可以进行切片操作,以截取某段字符:

>>> S = 'spam'
>>> S[0], S[−2] # Indexing from front or end 进行index操作
('s', 'a')
>>> S[1:3], S[1:], S[:−1] # Slicing: extract a section
('pa', 'pam', 'spa') # slice操作

6,切片的时候,包括写在左边的值,不包括写在右边的值。

7,三个参数的切片,X[I:J:K], 其中K表示步进step,如果不写K,则表示K位默认值+1.

8,步进可以是复数,这样的切片将得到倒着的字符串:

例子一:步进step = -1,获得倒序的字符串‘olleh’。

>>> S = 'hello'
>>> S[::.1] # Reversing items
'olleh'    

例子二:这里仍然包括offset 5,不包括offset 1,该记住:切片包括写在左边的offset,不包括写在右边的offset。

>>> S = 'abcedfg'
>>> S[5:1:−1] # Bounds roles differ
'fdec'

9,切片有时候可以用于截取文本中的某行字。通常来讲,每一行的结尾都是n,使用[:-1]即可以把n这个byte给去掉。虽然,人们更常用的是line.rstrip方法,因为有可能某行的行末未必有n.

10,ord()可以将某个字符转换为ASCII码,而chr则可以将ASCII码还原为所对应的字符。

11,int(‘1101’,2) 这个式子可以将二进制数1101,转换为十进制的integer。需要注意的是,1101需要加上‘’,2表示base。

12,string有个replace的方法,可以用来产生新的string。

>>> S = 'splot'
>>> S = S.replace('pl', 'pamal')
>>> S
'spamalot'

如果想要让Python只替换i次,需要填写它的第三个参数:

>>> S.replace('SPAM', 'EGGS', 1) # Replace one
'xxxxEGGSxxxxSPAMxxxx'

13,虽然string是immutable sequence, 需要做in-place change的话还是可以先将string转换为list,在用’’.join(some_list)的方法生成一个新的string。

14,string有一个split方法,可以将string以某特定的分界符将string切细,并返回一个list。

例子一:split()里面没有参数,代表的是whitespce(空格, 制表位,换行等,数量不限)

>>> line = 'aaa bbb ccc'
>>> cols = line.split()
>>> cols
['aaa', 'bbb', 'ccc']

例子二:以逗号作为分界符,将string切细并返回一个list。

>>> line = 'bob,hacker,40'
>>> line.split(',')
['bob', 'hacker', '40']

15,string的其他有用的方法:rstrip、upper、isalpha、endswith、startswith

16,格式化string有两种方法:
A: 类似于C语言的方法,String formatting expressions: ‘…%s…’ % (values)
B: 从C#/.NET引进的方法:
String formatting method calls: ‘…{}…’.format(values)

17, 针对方法A,下面的表格是格式的说明:

18,在%左边的格式是这样的:
%(keyname)widthtypecode
Keyname表示如果是dictionary的引用,这里写dictionary的key;
Flags: -号表示向左靠齐,0表示补零
Width 表示总共的位数
.precision 表示小数点右边要有多少位小数

19,下面的例子表示暂时不知道要有多少位小数,待传入值得时候确定:

>>> '%f, %.2f, %.*f' % (1/3.0, 1/3.0, 4, 1/3.0)
'0.333333, 0.33, 0.3333'  #这里最后选择了4位小数。

20,dictionary可以作为参数传入到这样的式子中:

>>> '%(qty)d more %(food)s' % {'qty': 1, 'food': 'spam'}
'1 more spam'

21,B方法:string format method 有如下4种基础类型:
Pass

22,更加复杂的如下面这种:

>>> somelist = list('SPAM')
>>> somelist
['S', 'P', 'A', 'M']
>>> 'first={0[0]}, third={0[2]}'.format(somelist)
'first=S, third=A'

23, A 方法使用 % 例子大全:

23.1 如果有两个参数,需要用括号将他们包围起来,括号前加%

>>> 'That is %d %s bird!' % (1, 'dead') # Format expression
That is 1 dead bird!

23.2 赋给一个variable代替%后面的内容

>>> exclamation = 'Ni'
>>> 'The knights who say %s!' % exclamation # String substitution
'The knights who say Ni!'

23.3 所有类型都可以使用%s,因为所有的object都可以转换为string。

>>> '%s -- %s -- %s' % (42, 3.14159, [1, 2, 3]) # All types match a %s target
'42 -- 3.14159 -- [1, 2, 3]'

23.4 –号表示向左靠齐。0表示用0补够数,6表示总共有6位

>>> x = 1234
>>> res = 'integers: ...%d...%−6d...%06d' % (x, x, x)
>>> res
'integers: ...1234...1234 ...001234'

23.5 小数点后面的数字表示小数位数

>>> '%−6.2f | %05.2f | %+06.1f' % (x, x, x)
'1.23 | 01.23 | +001.2'

23.6 %配合字典dictionary使用

>>> '%(qty)d more %(food)s' % {'qty': 1, 'food': 'spam'}
'1 more spam'

23.7 字典配合使用

>>> reply = """
Greetings...
Hello %(name)s!
Your age is %(age)s
"""
>>> values = {'name': 'Bob', 'age': 40} # Build up values to substitute
>>> print(reply % values) # Perform substitutions
Greetings...
Hello Bob!
Your age is 40

23.8字典配合使用

>>> template = '%(motto)s, %(pork)s and %(food)s'
>>> template % dict(motto='spam', pork='ham', food='eggs')
'spam, ham and eggs'

24 B方法例子

24.1通过绝对位置

>>> template = '{0}, {1} and {2}' # By position
>>> template.format('spam', 'ham', 'eggs')
'spam, ham and eggs'

24.2 通过key,可以不用引号

>>> template = '{motto}, {pork} and {food}' # By keyword
>>> template.format(motto='spam', pork='ham', food='eggs')
'spam, ham and eggs'

24.3 混合

>>> template = '{motto}, {0} and {food}' # By both
>>> template.format('ham', motto='spam', food='eggs')
'spam, ham and eggs'

24.4 通过相对位置

>>> template = '{}, {} and {}' # By relative position
>>> template.format('spam', 'ham', 'eggs') # New in 3.1 and 2.7
'spam, ham and eggs'

24.5 字典,属性一起混合使用,下面的1表示format括号里的第2个参数,0表示字典里的第一个参数。

>>> import sys
>>> 'My {1[kind]} runs {0.platform}'.format(sys, {'kind': 'laptop'})
'My laptop runs win32' 
>>> 'My {map[kind]} runs {sys.platform}'.format(sys=sys, map={'kind': 'laptop'})
'My laptop runs win32'

24.6 下面,0表示format()括号内的第一个参数,1表示第二个参数。冒号后面是格式,>号表示向左靠齐,<表示向左靠齐,10表示的是总需要十位

>>> '{0:>10} = {1:<10}'.format('spam', 123.4567)
' spam = 123.4567 '

24.7 如果冒号前面不写,则按照相对位置替换。

>>> '{:>10} = {:<10}'.format('spam', 123.4567)
' spam = 123.4567 '

24.8 在格式的位置用e f g来约束

>>> '{0:e}, {1:.3e}, {2:g}'.format(3.14159, 3.14159, 3.14159)
'3.141590e+00, 3.142e+00, 3.14159'
>>> '{0:f}, {1:.2f}, {2:06.2f}'.format(3.14159, 3.14159, 3.14159)
'3.141590, 3.14, 003.14'

24.9 在格式的位置用x,o,b来约束,进而显示十六进制、八进制、二进制数

>>> '{0:X}, {1:o}, {2:b}'.format(255, 255, 255) # Hex, octal, binary
'FF, 377, 11111111'

24.10 这里的1对应的是括号里的4,表示的是小数位数

>>> '{0:.{1}f}'.format(1 / 3.0, 4) # Take value from arguments
'0.3333'

24.11 在d前面,或者e,f,g等前面加上逗号,可以每三个数用逗号隔开

>>> '{0:,d}'.format(999999999999)
'999,999,999,999'

24.12 逗号要写在小数点的前面,如果他们都需要用到的话

>>> '{:,.2f}'.format(296999.2567)
'296,999.26'

24.13 显示tuple

>>> '{0}'.format((1.23,)) # Single value that is a tuple
'(1.23,)'

24.14 用关键字,对应于format里面的关键字

>>> '{num:d} = {title:s}'.format(num=7, title='Strings')
'7 = Strings'
    原文作者:derek
    原文地址: https://segmentfault.com/a/1190000008042426
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞