Anton Kovtoniuk
Anton Kovtoniuk

Reputation: 1

Replace multiple char in a row with one in a Python string

Let's say I have a string a = "a*****cd". Is there a way to turn it into "a*cd" for any amount of "*" without multiple loops? "*" is the only character which needs to be 'condensed', so the solution doesn't have to be universal in this regard.

Upvotes: 0

Views: 98

Answers (1)

Brooke Jackson
Brooke Jackson

Reputation: 166

We can use a regular expression :

import re
a = "a***********cd"
a = re.sub("\*+", "*", a)  

Let me explain : re.sub function replaces all matches of the regular expression (first argument) : "\*+" (one or more asterix) with "*" (second argument) in the string a (third argument)

Upvotes: 1

Related Questions