1

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?

1
  • Why RegEx and did you Google? Commented Feb 6, 2014 at 4:09

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

The reason I need regular expressions is because I might have a sentence that is: "This is a word. This is another word. H.E. Stein." And I want to be able to get rid of all the periods at the end of sentences but not acronyms.
@Mozbi, So you want "This is a word This is another word H.E. Stein" as a reuslt. Am I right?
Thanks a lot falsetru! you're awesome. Thanks for the exaplanations

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.