Julian
Julian

Reputation: 33

How to distinguish "..." to "." with Python

I would like to reshape a sentence with specific indications. More precisely, I would like to do the following :

sentence = "This is... a test."
reshaped_sentence = "This is ... a test ."

To do this I use replace() function :

sentence.replace("...", " ... ").replace(".", " . ")

But I obtain the following :

reshaped_sentence = "This is . . . a test ."

I really need to distinguish ... from . in my sentence, so any idea how to correct this problem ?

Upvotes: 3

Views: 43

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626903

You may use a regular expression to match either 3 consecutive dots or a single dot enclosed with 0 or more whitespace chars, and replace that with the match value enclosed with spaces. To get rid of the trailing or initial whitespace, just call strip().

See the Python demo:

import re
rx = r"\s*(\.{3}|\.)\s*"
s = "This is... a test."
print(re.sub(rx, r" \1 ", s).strip())
# => This is ... a test .

Here, \s*(\.{3}|\.)\s* matches

  • \s* - zero or more whitespaces
  • (\.{3}|\.) - Group 1 (referred to with \1 from the replacement pattern):
    • \.{3} - 3 dots
    • | - or
    • \. - a single dot
  • \s* - zero or more whitespaces

See the regex demo.

Upvotes: 1

Related Questions