Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

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

I want to replace repeated instances of the "*" character within a string with a single instance of "*". For example if the string is "***abc**de*fg******h", I want it to get converted to "*abc*de*fg*h".

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

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

where * is supposed to replace all instances of the "*" character. But I got: SyntaxError: unexpected character after line continuation character.

I also tried to manipulate it with a for loop like:

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

but this has the error where it only prints "*" because pattern2 = pattern[i] constantly redefines what pattern2 is...

Any help would be appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The naive way to do this kind of thing with re is

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

That replaces runs of 1 or more asterisks with one asterisk. For runs of exactly one asterisk, that is running very hard just to stay still. Much better is to replace runs of TWO or more asterisks by a single asterisk:

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

This can be well worth doing:

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

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

Note that re.sub will return a reference to the input string if it has found no matches, saving more wear and tear on your computer, instead of a whole new string.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...