Reputation: 1479
Is there a way to perform a sub on only one character of a matching pattern?
For example, if I have the string
"This is a word. This is another word. H.E. Stein"
and I want to perform a sub on just the '.'s at the end of a sentence so it becomes
"This is a word This is another word H.E. Stein"
How should I go about doing this?
Upvotes: 1
Views: 2756
Reputation: 369134
You don't need to use regular expression:
>>> "qwerty.".replace('.', '', 1) # 1 -> replace count (only once)
'qwerty'
To delete the last character, use slice:
>>> "qwerty."[:-1]
'qwerty'
UPDATE according to the question edit.
>>> text = "This is a word. This is another word. H.E. Stein"
>>> re.sub(r'(\w{2})\.', r'\1', text)
'This is a word This is another word H.E. Stein'
(\w{2})\.
: to match a period just after two word characters. capture the word characters as group 1. later referenced as \1
.
Upvotes: 3