Python 替换字符串

时间:2014-09-30 12:35:29   收藏:0   阅读:260

string类型是不可变的,因此不能采用直接赋值的方式。比如一个字符串 helloworld,想把o替换成z,那么只有先替换,然后再迭代。

strings="helloworld"
hello=strings.replace(o,z)
for index,string in enumerate(hello):
    print index,string

还有一种方法:

import string
table=string.maketrans(o,z)
for index,string in enumerate(strings.translate(table)):
    print index,string

 显示效果:

0 h
1 e
2 l
3 l
4 z
5 w
6 z
7 r
8 l
9 d

 

--End--

原文:http://www.cnblogs.com/ibgo/p/4001629.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!