次の複数行の文字列を考えてみましょう:
>> 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()行頭( ^) または行末 ( $) アンカーを使用するにはどうすればよいですか?