Python中replace方法实例分析,pythonreplace
Python中replace方法实例分析,pythonreplace
本文以实例形式讲述了Python中replace方法,很有实用价值,具体如下:
replace方法主要有两种:
last_date = "1/2/3" 目标为"123"
方法一:repalce
date =last_date.replace('/','')
方法二:re
p = re.compile("/") date = p.sub('', last_date)
需要注意的是:一定不要转义,否则函数不会生效。
replace 方法返回根据正则表达式进行文字替换后的字符串的复制,格式如下:
stringObj.replace(rgExp, replaceText)
参数:
stringObj 必选项。要执行该替换的 String 对象或字符串文字。该字符串不会被 replace 方法修改。
rgExp 必选项。为包含正则表达式模式或可用标志的正则表达式对象。也可以是 String 对象或文字。如果 rgExp 不是正则表达式对象, 它将被转换为字符串,并进行精确的查找;不要尝试将字符串转化为正则表达式。
replaceText 必选项。是一个String 对象或字符串文字,对于stringObj 中每个匹配 rgExp 中的位置都用该对象所包含的文字加以替换。在 Jscript 5.5 或更新版本中,replaceText 参数也可以是返回替换文本的函数。
例如:
content.replace('\n',' ').replace('\r',' ').replace('\\','\\\\').replace(',','\\,')
希望本文所述实例对大家的Python程序设计能起到一定的参考作用。
replace不是string模块的函数,而是String类的一个方法
s.replace('hello', 'good')
def string_with_2s(s): if not type(s)==type(''): raise TypeError slist=list(s) for i in range(0,len(slist),2): slist[i]='2' return ''.join(slist)以上为函数,调用方法为string_with_2s(字符串)
比如用下面语句
string_with_2s('abcd')
返回字符串'2b2d'
相关内容
- 零基础学Python(一)Python环境安装,基础学python环境
- python字符串连接方式汇总,python字符串汇总
- Python 不同对象比较大小示例探讨,python大小示例探讨
- Python中dictionary items()系列函数的用法实例,pythondictio
- Python中除法使用的注意事项,python除法
- python生成日历实例解析,python日历实例
- Python实现批量把SVG格式转成png、pdf格式的代码分享,
- Python创建日历实例,python日历实例
- 实例讲解Python中的私有属性,实例讲解python私有
- python实现的重启关机程序实例,python实例
评论关闭