Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace single instances of a character that is sometimes doubled

Tags:

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.

like image 929
Mariıos Avatar asked Dec 25 '15 16:12

Mariıos


People also ask

How to replace every instance of a character in a string Python?

The replace() method replace() is a built-in method in Python that replaces all the occurrences of the old character with the new character.

How do you replace every instance of a character in a string?

To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag.

How to replace only one character in string in Python?

replace() method helps to replace the occurrence of the given old character with the new character or substring. The method contains the parameters like old(a character that you wish to replace), new(a new character you would like to replace with), and count(a number of times you want to replace the character).

Which of the following is used to replace more than one character in a search?

Alternatively referred to as a wild character or wildcard character, a wildcard is a symbol used to replace or represent one or more characters.


1 Answers

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.

like image 130
timgeb Avatar answered Sep 30 '22 07:09

timgeb