string - How to replace repeated instances of a character with a single instance of that character in python -


i want replace repeated instances of "*" character within string single instance of "*". example if string "***abc**de*fg******h", want converted "*abc*de*fg*h".

i'm pretty new python (and programming in general) , tried use regular expressions , string.replace() like:

import re     pattern = "***abc**de*fg******h" pattern.replace("*"\*, "*") 

where \* supposed replace instances of "*" character. got: syntaxerror: unexpected character after line continuation character.

i tried manipulate loop like:

def convertstring(pattern): in range(len(pattern)-1):     if(pattern[i] == pattern[i+1]):         pattern2 = pattern[i] return pattern2 

but has error prints "*" because pattern2 = pattern[i] redefines pattern2 is...

any appreciated.

the naive way kind of thing re is

re.sub('\*+', '*', text) 

that replaces runs of 1 or more asterisks 1 asterisk. runs of 1 asterisk, running hard stay still. better replace runs of two or more asterisks single asterisk:

re.sub('\*\*+', '*', text) 

this can worth doing:

\python27\python -mtimeit -s"t='a*'*100;import re" "re.sub('\*+', '*', t)" 10000 loops, best of 3: 73.2 usec per loop  \python27\python -mtimeit -s"t='a*'*100;import re" "re.sub('\*\*+', '*', t)" 100000 loops, best of 3: 8.9 usec per loop 

note re.sub return reference input string if has found no matches, saving more wear , tear on computer, instead of whole new string.


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -