GokuShanth
GokuShanth

Reputation: 203

Replace multiple instances of a letter in a word with a single letter in Python

I have a string

line = "Pleeeeease"

To make it into Please by condensing multiple e's together. I know the code in Ruby

line.gsub!(/(.)\1{2,}/, '\1')

How do I do the same in Python?

Upvotes: 1

Views: 1059

Answers (2)

Padraic Cunningham
Padraic Cunningham

Reputation: 180482

A non regex way:

print("".join([ch if ch != line[ind+1:ind+2] else "" for ind, ch in enumerate(line)]))


In [44]: line = "Pleeeeeeeeeeasee"    
In [45]:  "".join([ch if ch != line[ind+1:ind+2] else "" for ind, ch in enumerate(line)])
Out[45]: 'Please'
In [46]: line = "Pleease"
In [47]:  "".join([ch if ch != line[ind+1:ind+2] else "" for ind, ch in enumerate(line)])
Out[47]: 'Please'

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174816

Use re.sub function.

>>> import re
>>> line = "Pleeeeease"
>>> re.sub(r'(.)\1{2,}', r'\1', line)
'Please'

This would replace three or more consecutive same character with that particular single character.

>>> re.sub(r'(.)\1+', r'\1', line)
'Please'

This would replace two or more consecutive same character with that particular single character.

Upvotes: 6

Related Questions