【发布时间】:2013-07-13 00:11:43
【问题描述】:
考虑以下多行字符串:
>> print s
shall i compare thee to a summer's day?
thou art more lovely and more temperate
rough winds do shake the darling buds of may,
and summer's lease hath all too short a date.
re.sub() 将所有出现的and 替换为AND:
>>> print re.sub("and", "AND", s)
shall i compare thee to a summer's day?
thou art more lovely AND more temperate
rough winds do shake the darling buds of may,
AND summer's lease hath all too short a date.
但是re.sub() 不允许^ 锚定到行首,所以添加它会导致and 的出现不会被替换:
>>> print re.sub("^and", "AND", s)
shall i compare thee to a summer's day?
thou art more lovely and more temperate
rough winds do shake the darling buds of may,
and summer's lease hath all too short a date.
如何将re.sub() 与行首 (^) 或行尾 ($) 锚点一起使用?
【问题讨论】:
标签: python regex string replace