python学习-字符串2

出自:https://blog.csdn.net/gavin_john/article/details/49835087

字符串转换工具

[python]  view plain  copy
  1. >>> int('42'),str(42)  
  2. (42'42')  
  3. >>> repr(42)  
  4. '42'  
int函数将字符串转换为数字,而str函数将数字转换为字符串表达形式
注意:repr函数的区别:

[python]  view plain  copy
  1. >>> print(str('spam'),repr('spam'))  
  2. spam 'spam'  
类似的内置函数可以把浮点数转换成字符串,或者把字符串转换成浮点数。

[python]  view plain  copy
  1. >>> str(3.1415),float("1.7")  
  2. ('3.1415'1.7)  
  3. >>> text = '1.234E-10'  
  4. >>> float(text)  
  5. 1.234e-10  
================================================================ =======================
字符串代码转换

单个的字符可以通过内置的ord函数转换为其对应的ASCII码——这个函数实际上返回的是这个字符在内存中对应的字符的二进制值。
而chr函数将会执行相反的操作,获取ASCII码并将其转化为对应的字符

[python]  view plain  copy
  1. >>> ord('s')  
  2. 115  
  3. >>> chr(115)  
  4. 's'  
可以利用循环完成对字符串内所有的字符的函数运算。这些工具也可以用来执行一种基于字符串的数学运算。
例如,为了生成下一个字符,我们可以预先将当前字符转换为整型并进行如下数学运算:

[python]  view plain  copy
  1. >>> S = '5'  
  2. >>> S = chr(ord(S)+1)  
  3. >>> S  
  4. '6'  
  5. >>> S = chr(ord(S)+1)  
  6. >>> S  
  7. '7'  
至少对于单个字符的字符串来说,可通过调用内置函数int,将字符串转换为整数
[python]  view plain  copy
  1. >>> int('5')  
  2. 5  
  3. >>> ord('5')-ord('0')  
  4. 5  
这样的转换可以与循环语句一起配合使用,例如,可以将一个表示二进制数的字符串转换为等值的整数。
每次都将当前的值乘以2,并加上下一位数字的整数值:(这个算法的思想是每次向左移位再加上新进来的数)

[python]  view plain  copy
  1. >>> B = '1101'  
  2. >>> I = 0  
  3. >>> while B != '':  
  4.     I = (I<<1)+(ord(B[0])-ord('0'))  
  5.     B = B[1:]  
  6.   
  7.       
  8. >>> I  
  9. 13  
这里的左移运算(I<<1)与乘以2的运算是一样的,不过左移运算一定要记得加括号,因为它的运算优先级很小。

=======================================================================================
修改字符串
字符串是不可变序列:不可变的意思就是不能再原地修改一个字符串(例如,给一个索引赋值)

[python]  view plain  copy
  1. >>> s = 'spqm'  
  2. >>> s[0]='x'  
  3. Traceback (most recent call last):  
  4.   File "<pyshell#1>", line 1in <module>  
  5.     s[0]='x'  
  6. TypeError: 'str' object does not support item assignment  
1.在Python中,若要改变一个字符串,需要利用合并、分片这样的工具来建立并赋值给一个新的字符串,
倘若必要的话,还要将这个结果赋值给字符串最初的变量名。

[python]  view plain  copy
  1. >>> s = s +'QPM'  
  2. >>> s  
  3. 'spqmQPM'  
  4. >>> s =s [:4]+'Gavin' +s[-1]  
  5. >>> s  
  6. 'spqmGavinM'  
2.还可以使用replace函数:

[python]  view plain  copy
  1. >>> s.replace('Gavin','Hello')  
  2. 'spqmHelloM'  
3.可以通过字符串格式化表达式来创建新的文本值:

[python]  view plain  copy
  1. >>> s = 'That is %d %s bird!'%(1,'dead')  
  2. >>> s  
  3. 'That is 1 dead bird!'  
  4. >>> y = 'That is {0} {1} bird!'.format(1,'dead')  
  5. >>> y  
  6. 'That is 1 dead bird!'  
  7.   
  8. >>> '%s'%[1,2,3]  
  9. '[1, 2, 3]'  
================================================================ =======================

字符串方法

1.find replace
合并操作和replace 方法每次返回一个新的字符串对象。实际上利用它们去修改字符串是一个潜在的缺陷。
如果不得不对一个超长字符串进行许多修改,为了优化脚本的性能,可能需要将字符串转换为一个支持原处修改的对象

[python]  view plain  copy
  1. >>> l = list(s)  
  2. >>> l  
  3. ['T''h''a''t'' ''i''s'' ''1'' ''d''e''a''d'' ''b''i''r''d''!']  
内置的list函数以任意序列中的元素创建一个新的列表,这样可以对其进行多次修改。
修改之后,如果需要将list转回字符串,可以用字符串方法join将列表合成一个字符串:

[python]  view plain  copy
  1. >>> z = ''.join(l)  
  2. >>> z  
  3. 'That is 1 dead bird!'  
2.join方法是通过设定的分隔符来调用。join将列表字符串连在一起,并用分隔符隔开,
上述例子中使用一个空的字符串分隔符将列表转换为字符串,一般的,对任何字符串分隔符和可迭代字符串都会是如下结果:

[python]  view plain  copy
  1. >>> 'Gavin'.join(['1','2','3','4'])  
  2. '1Gavin2Gavin3Gavin4'  
3.字符串的split方法将一个字符串分割为一个子字符串的列表

[python]  view plain  copy
  1. >>> cols = s.split()  
  2. >>> cols  
  3. ['That''is''1''dead''bird!']  
  4.   
  5. >>> ip = '198.172.1.16'  
  6. >>> c = ip.split('.')  
  7. >>> c  
  8. ['198''172''1''16']  
  9.   
  10. >>> line = "i'mSPAMaSPAMlumberjack"  
  11. >>> line.split('SPAM')  
  12. ["i'm", 'a', 'lumberjack']  
================================================================ =======================
更高级的字符串格式化表达式

代码意义
s字符串(或任何对象)
s,但使用repr,而不是str
字符
d十进制(整数)
i整数
无号(整数)
o八进制整数
x十六进制整数
Xx,但打印大写
e浮点指数
Ee,但打印大写
f浮点十进制
F浮点十进制
g浮点e或f
G浮点G或F
%常量%
[python]  view plain  copy
  1. >>> x = 1023456789  
  2. >>> x  
  3. 1023456789  
  4. >>> '%e | %f | %g'%(x,x,x)  
  5. '1.023457e+09 | 1023456789.000000 | 1.02346e+09'  
  6. >>> '%E'%x  
  7. '1.023457E+09'  
================================================================ =======================
基于字典的字符串格式化
看下例:

[python]  view plain  copy
  1. >>> '%(n)d  %(x)s'%{'n':1,'x':'spam'}  
  2. '1  spam'  
上例中,格式化字符串里(n)和(x)引用右边字典中的键,并提取它们相应的值。生成类似HTML或XML的程序往往利用这一技术。
你可以建立一个数值字典,并利用一个基于键的引用的格式化表达式一次性替换它们:

[python]  view plain  copy
  1. >>> reply = ''''' 
  2. Greetings... 
  3. Hello %(name)s! 
  4. Your age squared is %(age)s 
  5. '''  
  6. >>> values = {'name':'Bob','age':40}  
  7. >>> print(reply%values)  
  8.   
  9. Greetings...  
  10. Hello Bob!  
  11. Your age squared is 40  
这样的小技巧也常与内置函数vars配合使用,这个函数返回的字典包含了所有在本函数调用时存在的变量:

[python]  view plain  copy
  1. >>> food = 'spam'  
  2. >>> age = 40  
  3. >>> vars()  
  4. 'age'40'food''spam',...many more...}  
当字典用一个格式化操作的右边时,它会让格式化字符串通过变量名来访问变量(也就是说,通过字典中的键):

[python]  view plain  copy
  1. >>> '%(age)d %(food)s'%vars()  
  2. '40 spam'  
================================================================ =======================
字符串格式化调用方法

它和格式化表达式有很大程度的重合,并且有时比格式化表达式需要更多的代码,且在高级用途的时候很复杂
它使用主体字符串作为模板,并且接受任意多个表示将要根据模板替换的值的参数。
在主体字符串中,花括号通过位置(例如,{1})或关键字(例如,{food})指出替换目标及将要插入的参数。

[python]  view plain  copy
  1. #通过位置替换  
  2. >>> template = '{0}, {1} and {2}'  
  3. >>> template.format('spam','ham','eggs')  
  4. 'spam, ham and eggs'  
  5.   
  6. #通过参数替换  
  7. >>> template = '{motto} , {pork} and {food}'  
  8. >>> template.format(motto ='spam',pork='ham',food='eggs' )  
  9. 'spam , ham and eggs'  
  10.   
  11. #通过参数和位置替换  
  12. >>> template = '{motto},{0} and {food}'  
  13. >>> template.format('ham',motto = 'spam',food='eggs')  
  14. 'spam,ham and eggs'  
本质上呢,字符串也可以是创建一个临时字符串的常量,并且任意的对象类型都可以替换:
[python]  view plain  copy
  1. >>> '{motto},{0} and {food}'.format(42,motto=3.14,food=[1,2])  
  2. '3.14,42 and [1, 2]'  
----------------------------------------------------------------------------------------------------------- -------------------------------------------

添加键、属性和偏移量

格式化字符串可以指定对象属性和字典键,就像在常规python语法中一样,方括号指定字典键,而点表示位置或关键字所引用的一项的对象属性:

[python]  view plain  copy
  1. >>> 'My {1[spam]} runs {0.platform}'.format(sys,{'spam':'laptop'})  
  2. 'My laptop runs win32'  
  3.   
  4. >>> 'My {config[spam]} runs {sys.platform}'.format(config={'spam':'laptop'},sys = sys)  
  5. 'My laptop runs win32'  
格式化字符串中的方括号可以指定列表(以及其他序列)偏移量以执行索引,但是,只有单个的正的偏移量才能在格式化字符串的语法中有效:
[python]  view plain  copy
  1. >>> somelist  
  2. ['S''P''A''M']  
  3.   
  4. >>> 'first={0[-1]}'.format(somelist)  
  5. Traceback (most recent call last):  
  6.   File "<pyshell#36>", line 1in <module>  
  7.     'first={0[-1]}'.format(somelist)  
  8. TypeError: list indices must be integers, not str  
[python]  view plain  copy
  1. >>> 'first={0[1]}'.format(somelist)  
  2. 'first=P'  
所以,要指定负的偏移或者分片,或者使用任意表达式,必须在格式化字符串自身之外运行表达式:
[python]  view plain  copy
  1. >>> 'first = {0},last = {1}'.format(somelist[0],somelist[-1])  
  2. 'first = S,last = M'  
  3.   
  4. >>> parts = somelist[0],somelist[-1],somelist[1:3]  
  5. >>> 'first={0},last={1},middle={2}'.format(*parts)  
  6. "first=S,last=M,middle=['P', 'A']"  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值