替换有时会加倍的字符的单个实例 [英] Replace single instances of a character that is sometimes doubled

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

问题描述

我有一个字符串,每个字符由管道字符分隔(包括 "|" 本身),例如:

"f|u|n|n|y||b|o|y||a||c|a|t"

我想将所有不在另一个 "|" 旁边的 "|" 替换为空,以获得结果:

"funny|boy|a|cat"

我尝试使用 mytext.replace("|", ""),但这会删除所有内容并生成一个长字.

解决方案

这可以通过一个相对简单的正则表达式来实现,而无需链接str.replace:

<预><代码>>>>进口重新>>>s = "f|u|n|n|y||b|o|y||a||c|a|t">>>re.sub('\|(?!\|)' , '', s)'有趣|男孩|a|猫'

说明:\|(?!\|) 将查找后面没有另一个 | 字符的 | 字符.(?!foo) 表示否定前瞻,确保您匹配的任何内容后面都没有 foo.

I have a string with each character being separated by a pipe character (including the "|"s themselves), for example:

"f|u|n|n|y||b|o|y||a||c|a|t"

I would like to replace all "|"s which are not next to another "|" with nothing, to get the result:

"funny|boy|a|cat"

I tried using mytext.replace("|", ""), but that removes everything and makes one long word.

解决方案

This can be achieved with a relatively simple regex without having to chain str.replace:

>>> import re
>>> s = "f|u|n|n|y||b|o|y||a||c|a|t"
>>> re.sub('\|(?!\|)' , '', s)
'funny|boy|a|cat'

Explanation: \|(?!\|) will look for a | character which is not followed by another | character. (?!foo) means negative lookahead, ensuring that whatever you are matching is not followed by foo.

这篇关于替换有时会加倍的字符的单个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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