Replace single instances of a character that is so

2019-06-14 22:11发布

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.

7条回答
相关推荐>>
2楼-- · 2019-06-14 22:54

Use sentinel values

Replace the || by ~. This will remember the ||. Then remove the |s. Finally re-replace them with |.

>>> s = "f|u|n|n|y||b|o|y||a||c|a|t"
>>> s.replace('||','~').replace('|','').replace('~','|')
'funny|boy|a|cat'

Another better way is to use the fact that they are almost alternate text. The solution is to make them completely alternate...

s.replace('||','|||')[::2] 
查看更多
登录 后发表回答