Heim  >  Artikel  >  Backend-Entwicklung  >  Python中replace方法实例分析

Python中replace方法实例分析

WBOY
WBOYOriginal
2016-06-06 11:32:031321Durchsuche

本文以实例形式讲述了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程序设计能起到一定的参考作用。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn