如何在python中用该字符的单个实例替换字符的重复实例 [英] How to replace repeated instances of a character with a single instance of that character in python

查看:35
本文介绍了如何在python中用该字符的单个实例替换字符的重复实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 "*" 的单个实例替换字符串中 "*" 字符的重复实例.例如,如果字符串是 "***abc**de*fg******h",我希望它被转换为 "*abc*de*fg*h".

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".

我对 python(以及一般编程)很陌生,并尝试使用正则表达式和 string.replace() ,例如:

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("*"\*, "*")

其中 \* 应该替换*"字符的所有实例.但我得到:SyntaxError:行继续符后的意外字符.

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

我还尝试使用 for 循环来操作它,例如:

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

但这有一个错误,它只打印*",因为pattern2 = pattern[i] 不断地重新定义pattern2 是什么...

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

任何帮助将不胜感激.

推荐答案

re 做这种事情的天真的方法是

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

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

用一个星号替换 1 个或多个星号的运行.对于正好有一个星号的运行,这是为了保持静止而运行非常困难.用一个星号替换两个或更多个星号要好得多:

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)

这很值得:

\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

请注意,如果没有找到匹配项,re.sub 将返回对输入字符串的引用,从而为您的计算机节省更多的磨损,而不是一个全新的字符串.

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.

这篇关于如何在python中用该字符的单个实例替换字符的重复实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆