出自:https://blog.csdn.net/gavin_john/article/details/49835087
字符串转换工具
- >>> int('42'),str(42)
- (42, '42')
- >>> repr(42)
- '42'
注意:repr函数的区别:
- >>> print(str('spam'),repr('spam'))
- spam 'spam'
- >>> str(3.1415),float("1.7")
- ('3.1415', 1.7)
- >>> text = '1.234E-10'
- >>> float(text)
- 1.234e-10
字符串代码转换
单个的字符可以通过内置的ord函数转换为其对应的ASCII码——这个函数实际上返回的是这个字符在内存中对应的字符的二进制值。
而chr函数将会执行相反的操作,获取ASCII码并将其转化为对应的字符
- >>> ord('s')
- 115
- >>> chr(115)
- 's'
例如,为了生成下一个字符,我们可以预先将当前字符转换为整型并进行如下数学运算:
- >>> S = '5'
- >>> S = chr(ord(S)+1)
- >>> S
- '6'
- >>> S = chr(ord(S)+1)
- >>> S
- '7'
- >>> int('5')
- 5
- >>> ord('5')-ord('0')
- 5
每次都将当前的值乘以2,并加上下一位数字的整数值:(这个算法的思想是每次向左移位再加上新进来的数)
- >>> B = '1101'
- >>> I = 0
- >>> while B != '':
- I = (I<<1)+(ord(B[0])-ord('0'))
- B = B[1:]
- >>> I
- 13
=======================================================================================
修改字符串
字符串是不可变序列:不可变的意思就是不能再原地修改一个字符串(例如,给一个索引赋值)
- >>> s = 'spqm'
- >>> s[0]='x'
- Traceback (most recent call last):
- File "<pyshell#1>", line 1, in <module>
- s[0]='x'
- TypeError: 'str' object does not support item assignment
倘若必要的话,还要将这个结果赋值给字符串最初的变量名。
- >>> s = s +'QPM'
- >>> s
- 'spqmQPM'
- >>> s =s [:4]+'Gavin' +s[-1]
- >>> s
- 'spqmGavinM'
- >>> s.replace('Gavin','Hello')
- 'spqmHelloM'
- >>> s = 'That is %d %s bird!'%(1,'dead')
- >>> s
- 'That is 1 dead bird!'
- >>> y = 'That is {0} {1} bird!'.format(1,'dead')
- >>> y
- 'That is 1 dead bird!'
- >>> '%s'%[1,2,3]
- '[1, 2, 3]'
字符串方法
1.find replace
合并操作和replace 方法每次返回一个新的字符串对象。实际上利用它们去修改字符串是一个潜在的缺陷。
如果不得不对一个超长字符串进行许多修改,为了优化脚本的性能,可能需要将字符串转换为一个支持原处修改的对象
- >>> l = list(s)
- >>> l
- ['T', 'h', 'a', 't', ' ', 'i', 's', ' ', '1', ' ', 'd', 'e', 'a', 'd', ' ', 'b', 'i', 'r', 'd', '!']
修改之后,如果需要将list转回字符串,可以用字符串方法join将列表合成一个字符串:
- >>> z = ''.join(l)
- >>> z
- 'That is 1 dead bird!'
上述例子中使用一个空的字符串分隔符将列表转换为字符串,一般的,对任何字符串分隔符和可迭代字符串都会是如下结果:
- >>> 'Gavin'.join(['1','2','3','4'])
- '1Gavin2Gavin3Gavin4'
- >>> cols = s.split()
- >>> cols
- ['That', 'is', '1', 'dead', 'bird!']
- >>> ip = '198.172.1.16'
- >>> c = ip.split('.')
- >>> c
- ['198', '172', '1', '16']
- >>> line = "i'mSPAMaSPAMlumberjack"
- >>> line.split('SPAM')
- ["i'm", 'a', 'lumberjack']
更高级的字符串格式化表达式
代码 | 意义 |
s | 字符串(或任何对象) |
r | s,但使用repr,而不是str |
c | 字符 |
d | 十进制(整数) |
i | 整数 |
u | 无号(整数) |
o | 八进制整数 |
x | 十六进制整数 |
X | x,但打印大写 |
e | 浮点指数 |
E | e,但打印大写 |
f | 浮点十进制 |
F | 浮点十进制 |
g | 浮点e或f |
G | 浮点G或F |
% | 常量% |
- >>> x = 1023456789
- >>> x
- 1023456789
- >>> '%e | %f | %g'%(x,x,x)
- '1.023457e+09 | 1023456789.000000 | 1.02346e+09'
- >>> '%E'%x
- '1.023457E+09'
基于字典的字符串格式化
看下例:
- >>> '%(n)d %(x)s'%{'n':1,'x':'spam'}
- '1 spam'
你可以建立一个数值字典,并利用一个基于键的引用的格式化表达式一次性替换它们:
- >>> reply = '''''
- Greetings...
- Hello %(name)s!
- Your age squared is %(age)s
- '''
- >>> values = {'name':'Bob','age':40}
- >>> print(reply%values)
- Greetings...
- Hello Bob!
- Your age squared is 40
- >>> food = 'spam'
- >>> age = 40
- >>> vars()
- { 'age': 40, 'food': 'spam',...many more...}
- >>> '%(age)d %(food)s'%vars()
- '40 spam'
字符串格式化调用方法
它和格式化表达式有很大程度的重合,并且有时比格式化表达式需要更多的代码,且在高级用途的时候很复杂
它使用主体字符串作为模板,并且接受任意多个表示将要根据模板替换的值的参数。
在主体字符串中,花括号通过位置(例如,{1})或关键字(例如,{food})指出替换目标及将要插入的参数。
- #通过位置替换
- >>> template = '{0}, {1} and {2}'
- >>> template.format('spam','ham','eggs')
- 'spam, ham and eggs'
- #通过参数替换
- >>> template = '{motto} , {pork} and {food}'
- >>> template.format(motto ='spam',pork='ham',food='eggs' )
- 'spam , ham and eggs'
- #通过参数和位置替换
- >>> template = '{motto},{0} and {food}'
- >>> template.format('ham',motto = 'spam',food='eggs')
- 'spam,ham and eggs'
- >>> '{motto},{0} and {food}'.format(42,motto=3.14,food=[1,2])
- '3.14,42 and [1, 2]'
添加键、属性和偏移量
格式化字符串可以指定对象属性和字典键,就像在常规python语法中一样,方括号指定字典键,而点表示位置或关键字所引用的一项的对象属性:
- >>> 'My {1[spam]} runs {0.platform}'.format(sys,{'spam':'laptop'})
- 'My laptop runs win32'
- >>> 'My {config[spam]} runs {sys.platform}'.format(config={'spam':'laptop'},sys = sys)
- 'My laptop runs win32'
- >>> somelist
- ['S', 'P', 'A', 'M']
- >>> 'first={0[-1]}'.format(somelist)
- Traceback (most recent call last):
- File "<pyshell#36>", line 1, in <module>
- 'first={0[-1]}'.format(somelist)
- TypeError: list indices must be integers, not str
- >>> 'first={0[1]}'.format(somelist)
- 'first=P'
- >>> 'first = {0},last = {1}'.format(somelist[0],somelist[-1])
- 'first = S,last = M'
- >>> parts = somelist[0],somelist[-1],somelist[1:3]
- >>> 'first={0},last={1},middle={2}'.format(*parts)
- "first=S,last=M,middle=['P', 'A']"