Home  >  Article  >  Backend Development  >  python字符串替换的2种方法

python字符串替换的2种方法

WBOY
WBOYOriginal
2016-06-10 15:18:361728browse

python 字符串替换 是python 操作字符串的时候经常会碰到的问题,这里简单介绍下字符串替换方法。

python 字符串替换可以用2种方法实现:
1是用字符串本身的方法。
2用正则来替换字符串

下面用个例子来实验下:
a = 'hello word'
把a字符串里的word替换为python

1、用字符串本身的replace方法

复制代码 代码如下:

a.replace('word','python')

输出的结果是hello python

2、用正则表达式来完成替换:

复制代码 代码如下:

import re
strinfo = re.compile('word')
b = strinfo.sub('python',a)
print b

输出的结果也是hello python

至于用哪个方法的话,看你自己的选择了。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn