1, 字符串的链接concatenate有两种方式:
A:直接写在一块儿:express
>>> title = "Meaning " 'of' " Life" # Implicit concatenation >>> title 'Meaning of Life'
B:使用+号ui
2,raw string: 在string前面加r,就会是string的再也不具备转义功能。
应该注意的是,若是str的末尾是, Python仍然会将这个 和它后面的引号转义输出。这时候就不要用raw string了。this
3,Triple quotes code multiline block strings: 三个引号(单引号或者双引号)能够作创造多行的strings。此时不要在这里面的右边加入comment,不然会被当作string。spa
4,triple quotes还能够用来暂时的是某段代码disable。以下面:code
X = 1 """ import os # Disable this code temporarily print(os.getcwd()) """ Y = 2
5,字符串能够进行切片操做,以截取某段字符:orm
>>> 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,切片的时候,包括写在左边的值,不包括写在右边的值。ip
7,三个参数的切片,X[I:J:K], 其中K表示步进step,若是不写K,则表示K位默认值+1.ci
8,步进能够是复数,这样的切片将获得倒着的字符串:字符串
例子一:步进step = -1,得到倒序的字符串‘olleh’。get
>>> 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'