python replace 方法

replace 方法

返回根据正则表达式进行文字替换后的字符串的复制。stringObj.replace(rgExp, replaceText)

参数
stringObj
必选项。要执行该替换的 String 对象或字符串文字。该字符串不会被 replace 方法修改。

rgExp
必选项。为包含正则表达式模式或可用标志的正则表达式对象。也可以是 String 对象或文字。如果 rgExp 不是正则表达式对象,它将被转换为字符串,并进行精确的查找;不要尝试将字符串转化为正则表达式。

replaceText必选项。是一个String 对象或字符串文字,对于stringObj 中每个匹配 rgExp 中的位置都用该对象所包含的文字加以替换。在 Jscript 5.5 或更新版本中,replaceText 参数也可以是返回替换文本的函数。

例如:

content='(please) input your name:'

con=content.replace('(','')

print con |||| please) input your name


content.replace(' ',' ').replace(' ',' ').replace('\','\\').replace(',','\,')

---------------------

本文来自 MissZhang_ 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/u013052394/article/details/74002265?utm_source=copy
==================================================================================
描述
Python replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。
语法
replace()方法语法:
str.replace(old, new[, max])
参数
old -- 将被替换的子字符串。
new -- 新字符串,用于替换old子字符串。
max -- 可选字符串, 替换不超过 max 次
返回值
返回字符串中的 old(旧字符串) 替换成 new(新字符串)后生成的新字符串,如果指定第三个参数max,则替换不超过 max 次。
实例
以下实例展示了replace()函数的使用方法:
#!/usr/bin/python

str = "this is string example....wow!!! this is really string";
print str.replace("is", "was");
print str.replace("is", "was", 3);
以上实例输出结果如下:
thwas was string example....wow!!! thwas was really string
thwas was string example....wow!!! thwas is really string

原文地址:https://www.cnblogs.com/duanlinxiao/p/9820816.html