2009年2月16日星期一

Python查找并替换字符串

Python字符串提供了replace(old,new,maxreplace)方法,用新的文本替换指定的子字符串。replace方法接收一个查找字符串作为第一个参数,替换字符串作为第二参数。每一个查找到的字符串都将用一个新的字符串替换掉。作为可选,你可以指定一个最大的执行替换操作次数的数字作为第三个参数。

question = "What is the air speed velocity of \
an unlaiden swallow?"
print question
question2 = question.replace("swallow", \
"European swallow")
print question2
question3 = question.replace("swallow", \
"African swallow")
print question3

replace_str.py

What is the air speed velocity of an unlaiden
swallow?
What is the air speed velocity of an unlaiden
European swallow?
What is the air speed velocity of an unlaiden
African swallow?

Output from replace_str.py code

原文:<< Python Phrasebook: Essential Code and Commands>> Search and Replace in Strings

[声明]:限于译者水平,文中难免错漏之处,欢迎各位网友批评指正;

没有评论:

发表评论